【问题标题】:Shortest way to read this file line?读取此文件行的最短方法?
【发布时间】:2015-07-09 14:25:59
【问题描述】:

我有一个文件,其中包含如下所示的行:

Alice 60 30 75
Bob 20 250 12

其中名称和整数长度是可变的。将名称放入字符串并将整数放入大小为 3 的数组中的最短方法是什么?我做了一个 getline() 然后将第一个 char 推到第一个空间到一个 char 向量中,转移到字符串,然后将下一个 char 到空间,使用 atoi() 转换然后发送到数组等。我觉得有可能是更好的方法?

我尝试了以下建议:

int main() {
    ifstream infile("wheelgame.txt");
    string s;
    vector<int> a(3); 

    while (cin >> s >> a[0] >> a[1] >> a[2])
    {
        cout << "test";
    }

    }

但我想我是误会了?它永远这样运行。

【问题讨论】:

    标签: c++ file-io


    【解决方案1】:

    更短的方法

    std::string s;
    std::vector<int> a(3);    // or int a[3]; or std::array<int, 3> a;
    std::cin >> s >> a[0] >> a[1] >> a[2];
    

    编辑:将 while 循环更改为从文件读取而不是从标准输入(即 cin)

    while (infile >> s >> a[0] >> a[1] >> a[2]) {
        ...
    }
    

    这个循环不会永远运行。

    【讨论】:

    • 使用向量而不是数组会获得 +1。如果您不需要重新调整大小,最好使用std::array
    • 谢谢,看起来好多了。我不得不使用一个数组,因为我需要将它传递给一个采用 list[] 的函数,但这应该仍然可以正常工作。你还能用 getline() 吗?
    • @AustinMW 如果确实需要,您可以随时将矢量内容复制到数组中。
    • @AustinMW list[] 没问题,只要传入a.data()(或者&amp;a[0],如果你还在C++ 11之前)。
    • @AustinMW 不,使用while (cin &gt;&gt; s &gt;&gt; a[0] &gt;&gt; a[1] &gt;&gt; a[2]) {}
    【解决方案2】:

    如果您的字符串是 char 数组并且您不想使用 STL:

    char str[MAX];
    int a[3];
    fscanf(file, "%s %d %d %d", str, &a[0], &a[1], &a[2]);
    

    【讨论】:

      猜你喜欢
      • 2012-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-18
      • 1970-01-01
      • 1970-01-01
      • 2012-08-26
      相关资源
      最近更新 更多