1

Beginner here so please bear with me. So I am reading data from a csv file and I need to read data word by word and stop at the end of the line. This is the code.

fstream fops;
fops.open("file.csv");
string s;
do
{ 
  fops>>s;
}while(s!="\n");

However the loop continues to the next line until the file ends. Please help me out on this

VMH_97
  • 13
  • 2
  • 3
    `operator>>()` ignores whitespace. Use `getline()` instead to read an entire line. Alternatively, find a library to read and parse CSV files. – Code-Apprentice Oct 30 '19 at 17:15
  • Initially I did use getline(fops,s,'\n'). But I want to read it word by word so that I can assign each word to another variable. – VMH_97 Oct 30 '19 at 17:18
  • Related ( help for reading csv files): [https://stackoverflow.com/questions/1120140/how-can-i-read-and-parse-csv-files-in-c](https://stackoverflow.com/questions/1120140/how-can-i-read-and-parse-csv-files-in-c) – drescherjm Oct 30 '19 at 17:18
  • @Code-Apprentice Stop answering in comments – Lightness Races in Orbit Oct 30 '19 at 17:19

2 Answers2

7

I need to read data word by word and stop at the end of the line.

#include <sstream> // std::stringstream

fstream fops("file.csv");
if(fops) { // file opened
    string line;
    string word;
    // while(std::getline(fops, line)) { // to read all lines
    if(std::getline(fops, line)) {       // to read one line
        std::istringstream is(line);     // put the line in a stringstream
        while(is >> word) {              // extract word-by-word
            // use word
        }
    }
}
Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
2

operator>>() ignores whitespace. Use getline() instead to read an entire line. Alternatively, find a library to read and parse CSV files.

I want to read it word by word so that I can assign each word to another variable.

With operator>>() you cannot differentiate between a space ' ' and a new line '\n'. You should read an entire line and then parse the line into "words".

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268