Home > OS >  How to separate data from getline each time there is a space
How to separate data from getline each time there is a space

Time:10-07

int main() {
    ifstream billFile;
    billFile.open("bill.in"); //opening file

    if( billFile.is_open() ){
      string line1;
      
      getline(billFile, line1);

      cout << line1 << endl;
}

The bill.in file contains:

12 100

How can I separate 12 and 100 into two different variables?

CodePudding user response:

You can use std::istringstream to parse line1:

int main()
{
    ifstream billFile("bill.in"); //opening file
    if( billFile.is_open() )
    {
        string line1;
        if( getline(billFile, line1) )
        {
            istringstream iss(line1);
            int value1, value2;
            if( iss >> value1 >> value2 )
                cout << value1 << ' ' << value2 << endl;
        }
    }
}

Of course, if your file has only 1 line, then you can just omit getline(), eg:

int main()
{
    ifstream billFile("bill.in"); //opening file
    if( billFile.is_open() )
    {
        int value1, value2;
        if( billFile >> value1 >> value2 )
            cout << value1 << ' ' << value2 << endl;
    }
}

CodePudding user response:

I use the following split function to divvy up each line based on some set of delimiters (a space in your case).

std::vector<std::string> split(const std::string& str, 
                               std::string delims = " \t") {
    std::vector<std::string> strings;
    size_t start;
    size_t end = 0;
    while ((start = str.find_first_not_of(delims, end)) != std::string::npos) {
        end = str.find_first_of(delims, start);
        strings.push_back(str.substr(start, end - start));
    }
    return strings;
}

then you can split each line into a vector of strings:

int main() {
    ifstream billFile;
    billFile.open("bill.in"); //opening file
    if( billFile.is_open() ){
      string line;
      getline(billFile, line);
      std::vector<std::string> str = split(line, " ");
      std::string line1 = str[0];
      cout << line1 << endl;
   }
}

You use this method to split up strings using any delimiter you want.

CodePudding user response:

If you input file only contains one line and your keyboard is in very poor working order and you really need to minimize keystrokes you can write:

int main(){
    int v1, v2;
    if(std::ifstream("bill.in") >> v1 >> v2){
        // here you have valid v1 and v2.
    }
}

The >> "formatted input" is appropriate here because it is convenient to understand the contents of the text file as numbers.

CodePudding user response:

Function std::getline() takes delimitation as claimed in C reference. So just use getline(istream, str, ' ');.

Modify your codes as

int main() {
ifstream billFile;
billFile.open("bill.in"); //opening file

if( billFile.is_open() ){
  string line1;
  
  getline(billFile, line1, ' ');

  cout << line1 << endl;
}
  •  Tags:  
  • c
  • Related