【问题标题】:Cout the getline command for txt fileCout txt 文件的 getline 命令
【发布时间】:2018-05-05 19:56:30
【问题描述】:

我是 C++ 语言编程的新手。我正在尝试通过 C++ 语言读取文本文件(.txt 文件)。

我的文本文件名为 test.txt 的比赛如下:

1,3,5,7,9,8,1,2,3
0,2,4,6,8,8,1,2,3
1,3,5,7,9,8,1,2,3
0,2,4,6,8,8,1,2,3

我写了如下代码来读取test.txt:

#include<stdio.h>
#include<iostream>
#include<string>
#include<sstream>
#include<stdlib.h> // atoi -> Convert string to int number
#include<fstream> // need for read file
using namespace std;
int main(){
  string tenfile;
  cout<<"Ten file: ";
  cin >> tenfile;
  cout<<tenfile.c_str()<<endl;
  int i,j;    
  int value;
  string data; // declare data in file
  ifstream myfile (tenfile.c_str());
  while(myfile.good())
    {
      getline(myfile,data,','); // use ' ' not " "
      cout << "data: " << data << endl;
    }
myfile.close();
return 0;
}

当我运行这段代码来读取 test.txt 时,我在屏幕上看到如下:

Ten file: test.txt
test.txt
data: 1
data: 3
data: 5
data: 7
data: 9
data: 8
data: 1
data: 2
data: 3
0
data: 2
data: 4
data: 6
data: 8
data: 8
data: 1
data: 2
data: 3
1
data: 3
data: 5    
data: 7
data: 9
data: 8
data: 1
data: 2
data: 3
...

当我看到筛选值时,我意识到 第 2 行、第 3 行和第 4 行的第一个值 没有 data: 。我只看到了0,1,0。

我该如何解决这个问题?我想在我的 C++ 代码中解决这个问题,不想修改 test.txt 文件。

谢谢,

【问题讨论】:

标签: c++


【解决方案1】:

输入由逗号',' 分隔,而不是getline(myfile,data,','); 中的换行符分隔。因此,当您到达文本文件中的行尾时,getline 函数会看到下一个字符序列,直到下一个逗号是“3\n0”,其中“\n”是换行符。

然后,您的程序打印“3\n0”,输出为:

data: 3
0

您的程序仍在打印输出。

一个简单的解决方案是确保将文本文件中的每一行末尾都替换为逗号,以便所有值都在一行上。

另一种解决方案是检查您的数据是否包含换行符,并根据换行符的位置拆分字符串。

您也可以更改程序以读取整行,然后通过逗号字符拆分或标记数据。

在此处了解有关字符串标记化的更多信息:
Multiple methods of string tokenizing
Tokenizing a string with strstream

【讨论】:

    【解决方案2】:

    我为isdigit 函数添加了一个库,并改变了您读取文件的方式。你可以在注释以&lt;&lt;------开头的地方找到我的代码解释

    #include<stdio.h>
    #include<iostream>
    #include<string>
    #include<sstream>
    #include<stdlib.h> // atoi -> Convert string to int number
    #include<fstream> // need for read file
    #include<cctype> // <<------ Included this for isdigit
    using namespace std;
    
    int main() {
        string tenfile;
        cout << "Ten file: ";
        cin >> tenfile;
        cout << tenfile << endl; // <<------ Removed .c_str() you don't need it
        int i, j;
        int value;
    
        ifstream myfile(tenfile); // <<------ Removed .c_str() you don't need it
        char c;
        while (myfile.get(c)) // <<------ Reading file char by char
        {
            //getline(myfile, data, ','); // use ' ' not " "
            if (isdigit(c)) // <<------ If char is a digit
                cout << "data: " << c << endl; // <<------ Print that char
        }
        myfile.close();
        return 0;
    }
    

    这是上面代码的结果:

    data: 1
    data: 3
    data: 5
    data: 7
    data: 9
    data: 8
    data: 1
    data: 2
    data: 3
    data: 0
    data: 2
    data: 4
    data: 6
    data: 8
    data: 8
    data: 1
    data: 2
    data: 3
    data: 1
    data: 3
    data: 5
    data: 7
    data: 9
    data: 8
    data: 1
    data: 2
    data: 3
    data: 0
    data: 2
    data: 4
    data: 6
    data: 8
    data: 8
    data: 1
    data: 2
    data: 3
    

    如果你不想为isdigit函数添加一个新的库,你可以自己写。基本上是这样的:

    int check_digit (char c) {
        if ((c>='0') && (c<='9'))
            return 1;
        return 0;
    }
    

    之后您可以使用check_digit(c) 而不是isdigit(c) 并且可以删除#include&lt;cctype&gt;


    可以读取任意大小的版本:

    #include<iostream>
    #include<string>
    #include<fstream> // need for read file
    #include <locale>
    using namespace std;
    
    int count_words(const char*);
    
    int main() {
        string tenfile;
        cout << "Ten file: ";
        cin >> tenfile;
        cout << tenfile << endl; // <<------ Removed .c_str() you don't need it
    
        ifstream myfile(tenfile); // <<------ Removed .c_str() you don't need it
    
        unsigned int i;
        string full_text;
        getline(myfile, full_text, static_cast<char>(myfile.eof()));
    
        for (i = 0; i < full_text.size(); i++)
        {
            if (full_text[i] == '\n')
                full_text[i] = ' ';
            if (full_text[i] == ',')
                full_text[i] = ' ';
        }
    
        const unsigned int word_count = count_words(full_text.c_str());
    
        unsigned int k = 0;
        string display_text;
        for (i = 0; i < word_count; i++)
        {
            while (full_text[k] != ' ')
            {
                display_text += full_text[k];
                k++;
                if(k > full_text.size())
                {
                    k = full_text.size();
                    break;
                }
            }
    
            if (full_text[k] == ' ')
                k++;
    
            cout << "data: " << display_text << "\n";
            display_text.clear();
        }
    
        myfile.close();
        return 0;
    }
    
    int count_words(const char* str)
    {
       bool in_spaces = true;
       int num_words = 0;
    
       while (*str != NULL)
       {
          if (*str == ' ')
          {
             in_spaces = true;
          }
          else if (in_spaces)
          {
             num_words++;
             in_spaces = false;
          }
    
          ++str;
       }
    
       return num_words;
    }
    

    输入文件:

    10,3,5,7,9,8,1,2,3
    0,2,4,6,198,8,1,2,3
    1,3,5,7,9,8,1,2,3
    0,2,4,6,8,8,1,2,3000
    

    输出:

    Ten file: binStr.txt
    binStr.txt
    data: 10
    data: 3
    data: 5
    data: 7
    data: 9
    data: 8
    data: 1
    data: 2
    data: 3
    data: 0
    data: 2
    data: 4
    data: 6
    data: 198
    data: 8
    data: 1
    data: 2
    data: 3
    data: 1
    data: 3
    data: 5
    data: 7
    data: 9
    data: 8
    data: 1
    data: 2
    data: 3
    data: 0
    data: 2
    data: 4
    data: 6
    data: 8
    data: 8
    data: 1
    data: 2
    data: 3000
    

    【讨论】:

    • 我想问一下,如果我在 test.txt 文件中的值大于 10。我可以使用 isdigit() 打印正确的值吗?
    • @TaiChau 因为我们正在逐个读取字符,所以它将检测为 10 作为 1 和 0。将打印 data: 1 data: 0 代替。你想要这个问题的替代解决方案吗?我会写。
    • 是的。请给我一个超过 10 的值的解决方案。我想打印超过 10 的值或像这样的大数字:10 -> data: 10192 -> data: 192乙>。谢谢
    • @TaiChau 我已经完成了,现在更新我的答案。
    • 非常感谢您的解决方案。但是你能解释一下这个说法吗?我真的不明白。否则 if (in_spaces) { num_words++; in_spaces = 假; }。为什么 in_spaces=false ?
    【解决方案3】:

    我会做出这些改变:

    • 明确使用std 符号
    • 逐行读取外部读取
    • 为内部读取逐个读取数据
    • 剔除不需要的#include
    • 删除死变量
    • 打开所有编译器警告并解决它们
    • 使用自动(因为我属于“几乎总是使用自动”阵营)

    所以我的代码版本如下所示:

    #include <fstream>
    #include <iostream>
    #include <sstream>
    #include <string>
    
    using std::cin;
    using std::cout;
    using std::endl;
    using std::getline;
    using std::ifstream;
    using std::istringstream;
    using std::string;
    
    int main()
    {
      auto tenfile = string{};
      cout << "Ten file: ";
      getline(cin, tenfile);
      cout << tenfile << endl;
      auto myfile = ifstream{tenfile};
      auto line = string{};
    
      while (getline(myfile, line))
      {
        auto myline = istringstream(line);
        auto data = string{};
    
        while (getline(myline, data, ','))
        {
          cout << "data: " << data << endl;
        }
      }
    
      myfile.close();
    }
    

    【讨论】:

      猜你喜欢
      • 2022-01-25
      • 2012-11-14
      • 2018-11-01
      • 1970-01-01
      • 2018-06-15
      • 2019-03-23
      • 2021-10-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多