【问题标题】:Detect newline byte from filestream从文件流中检测换行字节
【发布时间】:2009-03-13 00:13:36
【问题描述】:

我正在尝试从包含组织名称(不含空格)和浮点整数的文本文件中收集信息。我想将此信息存储在数组结构中。

到目前为止,我遇到的问题是收集信息。这是文本文件的示例:

CBA 12.3 4.5 7.5 2.9 4.1

TLS 3.9 1 8.6 12.8 4.9

每个组织最多可以有 128 个不同的号码,文本文件中最多可以有 200 个组织。

这是我目前的结构:

struct callCentre
{
char name[256];
float data[20];
};

我的主要:

int main()
{
callCentre aCentre[10];
getdata(aCentre);
calcdata(aCentre);
printdata(aCentre);
return 0;
}

还有getdata函数:

void getdata(callCentre aCentre[])
{
ifstream ins;
char dataset[20];

cout << "Enter the name of the data file: ";
cin >> dataset;

ins.open(dataset);

if(ins.good())
{
    while(ins.good())
    {
        ins >> aCentre[c].name;
        for(int i = 0; i < MAX; i++)
        {
            ins >> aCentre[c].data[i];
            if(ins == '\n')
                break;
        }
        c++;
    }
}
else
{
    cout << "Data files couldnt be found." << endl;
}
ins.close();
}

我试图在我的 getdata 函数中实现的是:首先将组织名称存储到结构中,然后将每个浮点数读取到数据数组中,直到程序检测到换行字节。但是,到目前为止,我对换行字节的检查不起作用。

假设变量 cMAX 已经定义。

我应该如何正确处理?

【问题讨论】:

    标签: c++ newline text-files fstream


    【解决方案1】:

    >> 运算符将空格视为分隔符,其中包括换行符,因此它只会吃掉那些,而你永远看不到它们。

    【讨论】:

    • 不是真的,它会吃掉所有的东西,直到出现空白字符,下次调用它时,它会跳过空白字符,直到它到达另一个空白字符。 "hello there" 会导致 hello 被吃掉,而 "there" 仍然存在。
    • 续。使用 .peek() 你可以检查下一个字符是什么。
    • @X-Istence 用“吃掉”我的意思是他们被跳过了,你没有看到他们。在 "hello \n there" 上使用 >> 的两次结果是 "hello" 和 "there",对吧?
    【解决方案2】:

    您需要阅读行,然后将行截断。下面的一些hackery说明了基本思想:

    #include <iostream>
    #include <string>
    #include <sstream>
    using namespace std;
    
    int main() {
        string line;
        while( getline( cin, line ) ) {
            istringstream is( line );
            string cs;
            is >> cs;
            double vals[10];
            int i = 0;
            while( is >> vals[i] ) {
                i++;
            }
    
            cout << "CS: " << cs;
            for ( int j = 0; j < i; j++ ) {
                cout << " " << vals[j];
            }
            cout << endl;
        }
    }
    

    【讨论】:

      【解决方案3】:
      char byte = ins.peek();
      

      或者

      if(ins.peek() == '\n') break;
      

      (编辑):您还需要在 peek() 之后检查 eof,因为某些文件可能没有结束换行符。

      我想指出,您可能需要考虑使用vector&lt;callCentre&gt; 而不是静态数组。如果您的输入文件长度超过了数组的容量,您将遍历整个堆栈。

      【讨论】:

      • 这正是我想要的。谢谢。
      【解决方案4】:

      我会逐行读取文件,并单独解析每一行的值:

      std::string line;
      while (std::getline(ins, line)) {
        std::istringstream sline(line);
        sline >> aCentre[c].name;
        int i = 0;
        while (sline >> aCentre[c].data[i])
          i++;
        c++;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-07-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-11-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多