c++ - 谁能告诉我我用getline格式化(cpp)出错了

标签 c++ format getline

尝试使用c++ getline函数进行格式化。输出将所有内容放在第一个记录编号的姓氏上,而不是放在哪里。

码:

#include <fstream>
#include <string>
#include <iostream>
using namespace std;

int main()
{
    const int RANGE = 12;
    string tab[RANGE];
    int i = 0, j = 0;
    ifstream reader("records.txt");
    if (!reader)
    {
        cout << "Error opening input file" << endl;
        return -1;
    }
    while (!reader.eof())
    {
        if ( ( i + 1) % 4 == 0)
            getline( reader, tab[i++], '\n');
        else
            getline( reader, tab[i++], '\t');
    }
    reader.close();
    i = 0;
    while (i < RANGE)
    {
        cout << endl << "Record Number: " << ++j << endl;
        cout << "Forename: " << tab[i++] << endl;
        cout << "Surname: " << tab[i++] << endl;
        cout << "Department: " << tab[i++] << endl;
        cout << "Telephone: " << tab[i++] << endl;
    }
    return 0;
}

TXT文件的内容:
John    Smith    Sales    555-1234
Mary    Jones    Wages    555-9876
Paul    Harris   Accts    555-4321

请自己运行代码以了解会发生什么,然后将txt文件与代码放在同一文件夹中。

希望有人可以帮助我,谢谢。

最佳答案

在istream中有更简单的方法来分隔单词,即C++ sring流工具:

#include <fstream>
#include <iostream>
#include <sstream>  //<-- string stream library

using namespace std; //<-- should not be used, use scope std::

int main() {

    const int RANGE = 12;
    string tab[RANGE];
    string temp;       //<--to store each field temporarily
    int i = 0, j = 0;
    ifstream reader("records.txt");
    if (!reader) {
        cout << "Error opening input file" << endl;
        return -1;
    }
    while (getline(reader, temp)) { //<-- read one full line
        stringstream ss(temp); // <-- input to a string stream
        while(ss >> tab[i]){   // <-- passing strings to the string array one by one
            i++;
        }
    }
    reader.close();
    i = 0;
    while (i < RANGE) {
        cout << endl << "Record Number: " << ++j << endl;
        cout << "Forename: " << tab[i++] << endl;
        cout << "Surname: " << tab[i++] << endl;
        cout << "Department: " << tab[i++] << endl;
        cout << "Telephone: " << tab[i++] << endl;
    }
    return 0;
}

这里的想法是使您的代码尽可能地困惑,我建议的一件事是使用std::vector而不是常规的固定大小数组。另外,正如所说和链接的那样,eof是非常不可靠的。

关于c++ - 谁能告诉我我用getline格式化(cpp)出错了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59994747/

相关文章:

c++ 从 .csv 文件中读取

当到达字符串末尾时,C++ getline 导致段错误

c++ - getline 没有为字符串对象赋值

C++ 在主函数中使用来自一个类的成员函数?

c++ - 无法从文件 C++ 中读取 double 行

Php自定义日期格式及比较

C# 字符串格式

c++ - 我们如何使用 Google bazel 运行单个测试

c++ - 不可能的堆栈跟踪?尽管已检查,但使用this = nullptr的访问冲突

带有 SQL 通配符和 LIKE 的 Python 字符串格式