【问题标题】:How do I read comma seperated numbers from a file into an array in C++? [duplicate]如何将逗号分隔的数字从文件读入 C++ 中的数组? [复制]
【发布时间】:2020-10-23 06:09:58
【问题描述】:

我必须从文件中读取的数字如下所示: 1,5,26,3,86,35

我设法分别读取每个数字,但我的问题是数字超过一位。例如 26 或 86。

如何将它们读为一个数字而不是 2 6 和 8 6?

这是我目前所拥有的:

    int main()
{
    fstream numbers;
    string line;
    int num;
    
    numbers.open("test.txt");
    
    if(!(numbers))
        cout<<"error: file could not be read."<<endl;
    
    while(getline(numbers,line))
    {
        for(int i = 0; i<line.length();i++)
        {
            if(isdigit(line[i]))
                cout<<line[i]<<endl;
        }
    }
}

谢谢。

【问题讨论】:

  • 您在互联网上搜索“c++ 读取文件逗号分隔”。已经有太多例子了。
  • 简单(如果有点慢)的方法是getline 获取一行并将该行放入istringstream 然后在istringstream 上使用getline 以逗号分隔而不是换行符。根据您的需要转换生成的令牌。我会四处寻找,看看能不能找到一个重复的。
  • 这很好,但可能有点过于笼统:stackoverflow.com/questions/1120140/…
  • 在 Google 中弹出 read comma separator numbers in C++ site:stackoverflow.com 将提供许多替代方案。

标签: c++ file


【解决方案1】:

您可以使用operator&gt;&gt; 使其更简单

#include <fstream>
#include <iostream>
#include <string>

int main() {
    std::fstream numbers("test.txt");
    int num;

    if(!(numbers)) std::cout<<"error: file could not be read.\n";
    
    while(numbers >> num) {
        std::cout<<num<<'\n';
        numbers.ignore();
    }
}

【讨论】:

  • OP 想要读取逗号分隔的数字。重复项是关于 CSV 的。这个问题的答案和骗子的答案在复杂性上存在很大差异。如果可以用 15 行代码解决问题,为什么 OP 还要实现 CSV 解析器?
  • 我又添加了 2 个处理逗号分隔数字的 dup,我喜欢你的回答,所以你也得到了支持。 :)
【解决方案2】:

这可以使用 istringstream 类来完成。这只是像 cin 这样的流对象。 您可以通过以下方式使用它:

int main(){
    string str = "10,20,30,40,50";
    istringstream iss(str);           // create an istringstream class object and pass 
                                      //    the string as argument.
    int k;
    while(iss >> k){
        cout << k << endl;
        if(iss.peek() == ',')                // check if the next character is a comma 
                                             // or any other delimiter and ignore it
            iss.ignore();
    }


    return 0;
}

它应该工作。这可用于从具有任何分隔符的任何字符串中提取值。

【讨论】:

    猜你喜欢
    • 2023-02-02
    • 1970-01-01
    • 2023-03-15
    • 2016-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多