繁体   English   中英

如何在C ++中解析带有空格的文件?

[英]How to parse a file with blank spaces in c++?

我有一个格式为的文件:

2
3 4
7 8 9
10 20 22 02
...

每行基本上是数字,以空格分隔。 我必须从文件中读取,提取所有数字并维护它们的行号,因为稍后我必须制作一棵树。 我这样做是为了接受输入,但得到奇怪的输出。

#include<cstdio>
#include<iostream>
#include<cctype>
using namespace std;

void input()
{
    char c,p;
    while(c=getchar()!=EOF)
    {
        if(c=='\n') printf("},\n{");
        else if(c==' ') printf(",");
        else if(c=='0')
        {
            p=getchar();
            if(p==' ')
            {
                printf("%c%c,",c,p);
            }
            else
            {
                printf("%c,",p);
            }
        }
        else if(isalpha(c))
        {
            printf("%c",c);
        }
    }
}


int main()
{
    input();
}

该图显示了输入和输出 在此处输入图片说明

您编写的C比C ++更多。

在C ++中,您可以使用流。 使用peek()检查下一个字符,并>>实际读取它。

例如:

using namespace std;
int main(){
  ifstream s("/tmp/input");
  int nr;
  while (!s.eof()) {
    switch (s.peek()){
      case '\n': s.ignore(1); cout << "},\n{"; break;
      case '\r': s.ignore(1); break;
      case ' ': s.ignore(1);  cout << ", "; break;
      default: if (s >> nr) cout << nr; 
    }
  }
}

使用文件流,逐行读取并使用stringstream解析每一行:

std::ifstream file("filename");
std::string line;
size_t line_number(1);
while ( std::getline(file, line) ) // reads whole lines until no more lines available
{
    std::stringstream stream(line);
    int tmp;
    std::cout << "Numbers in line " << line_number << ":";
    while ( stream >> tmp ) // reads integer divided by any whitespace until no more integers available
    {
        std::cout << " " << tmp;
    }
    std::cout << "\n";
    ++line_number;
}

您需要包括

#include <iostream> // for std::cout
#include <string>   // for std::string
#include <fstream>  // for std::ifstream
#include <sstream>  // for std::stringstream

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM