【问题标题】:C++ populate array elements with ifstreamC++ 使用 ifstream 填充数组元素
【发布时间】:2020-05-02 20:17:15
【问题描述】:

我正在尝试从具有“|”的文本文件中填充字符串数组分隔符。现在我将整个文件填充到数组的第一个元素中。我希望每个字符串都填充下一个数组元素。

ifstream infile;
infile.open("info.dat");
string line;
int counter = 0;
while (getline(infile, line))
{
    getline(infile ,line ,'|');
    b[counter] = line;
    counter++;
    cout << endl;
}
infile.close();

cout << b[0] << endl << b[1];
return 0;
}

b[0] 包含整个文件,而b[1] 为空。这是.dat 文件包含的内容。

green dog|red fish|brass monkey|purpe elephant||||||||||||

我正在尝试使用 b[] 数组来分隔字符串。在底部的cout 中,我期待“绿狗”打印在控制台的第一行,“红鱼”打印在控制台的第二行。

【问题讨论】:

  • 您的程序打印什么
  • 您调用getline(infile, line) 时没有在第三个参数中传递分隔符。读取到行尾或文件结束,以先到者为准。

标签: c++ arrays delimiter


【解决方案1】:

这个

while (getline(infile, line))
{
    getline(infile ,line ,'|');

应该是这样的

while (getline(infile, line, '|'))
{

我不知道为什么当你有“|”时你选择了第一个选项分隔数据。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-14
    • 1970-01-01
    • 2023-03-07
    • 1970-01-01
    • 2013-03-03
    相关资源
    最近更新 更多