代码之家  ›  专栏  ›  技术社区  ›  Saveliy Mizerovskiy

getline()跳过c中CSV文件中的前两个字符++

  •  -3
  • Saveliy Mizerovskiy  · 技术社区  · 1 年前

    我的代码应该从CSV文件中读取数学问题,然后检查它们的答案是否正确,但每当我使用 getline() 它只是没有从每行中获取前两个字符。 (也忽略那些来自我必须使用的基本文件的注释)

    我的代码:

    #include <iostream>
    #include <fstream>
    #include <cstdlib>
    #include <climits>
    #include <vector>
    #include <string>
    using namespace std;
    int main(){
        fstream fin;
        int comma;
        float cans, sans, question, correct;
        fin.open("problems.csv");
        if (fin.fail()) {
            cerr << "File cannot be opened for reading." << endl;
            exit(1); // exit if failed to open the file
        }
        vector<string> row;        // new string variable
        string line, word, temp, problem; 
        correct = 0;
        question = 0;
        while(fin >> temp) { 
            question ++;
            row.clear();
            // this loop reads the file line-by-line
            // extracting 5 values on each iteration
            getline(fin, line);
            comma = line.find(",");
            cans = stod(line.substr(comma + 1));
            cout << "(" << question << ") " << line.substr(0,comma) << "? ";
            cin >> sans;
            if (sans == cans){
                cout << "true" << endl;
                correct ++;
            } else {
                cout << "false" << endl;
            }
            fin.ignore(INT_MAX, '\n'); //skips to the end of line, 
                                //ignorring the remaining columns 
        
            // for example, to print the date and East basin storage:
            //cout << date << " " << eastSt << endl;
        }
    }
    

    csv文件:

    my csv file

    代码输出:

    my code output

    我试着使用 temp 而不是 line ,但后来我转换为 int s不起作用。

    1 回复  |  直到 1 年前
        1
  •  0
  •   Remy Lebeau    1 年前

    如评论中所述,您正在将每行的前几个字符读入 temp 然后你忽略了它。

    您需要更换此:

    while(fin >> temp)

    取而代之的是:

    while (getline(fin, line))

    然后你可以解析 line 根据需要。