C++: Read from text file and separate into variable

前端 未结 3 1109
遇见更好的自我
遇见更好的自我 2020-12-03 15:10

I have this in a text file:

John 20 30 40
mike 30 20 10

How do i read from the text file and separate them into variable name, var1, var2,

相关标签:
3条回答
  • 2020-12-03 15:38

    I think that when the numbers were printed out in a group with no spaces, the reason was just that you need to put spaces in between the variable, like this:

    cout << name << " " << var1 << " " << var2 << " " << var3 << "\n";
    
    0 讨论(0)
  • 2020-12-03 15:45

    It looks like you need to declare var1, var2, and var3.

    Also instead of this:

          getline (myfile,name,'\t');
          getline (myfile,var1,'\t');
          getline (myfile,var2,'\t');
          getline (myfile,var3,'\t');
    

    Try this:

      myfile >> name;
      myfile >> var1;
      myfile >> var2;
      myfile >> var3;
    

    Not because what you had is wrong, but the second is cleaner and will handle all white space.

    0 讨论(0)
  • 2020-12-03 15:49

    Something like this should work (I don't have a compiler handy, so you may need to tweak this a little):

    #include <iostream>
    #include <sstream>
    using namespace std;
    
    
    int main()
    {
        ifstream inputFile("marks.txt");
        string line;
    
        while (getline(inputFile, line))
        {
            istringstream ss(line);
    
            string name;
            int var1, var2, var3;
    
            ss >> name >> var1 >> var2 >> var3;
        }
    }
    

    Edit: Just saw this again, I don’t know why I chose the get line approach earlier. Doesn’t the following (simpler solution) work?

    #include <fstream>
    using namespace std;
    
    int main()
    { 
        ifstream fin(“marks.txt”);
    
        string name;
        int var1;
        int var2;
        int var3;
    
        while (fin >> name >> var1 >> var2 >> var3)
        {
            /* do something with name, var1 etc. */
            cout << name << var1 << var2 << var3 << “\n”;
        }
    }
    
    0 讨论(0)
提交回复
热议问题