简体   繁体   中英

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

I have a file of format as:

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

basically numbers in each line , separated by spaces. I have to read from the file, extract all numbers and maintain their line number too, as I have to make a tree later. I'm doing this to take input, but getting weird outputs.

#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();
}

The image shows the input and output 在此处输入图片说明

You are writing more C than C++.

In C++ you can use streams. Use peek() to check the next character, and >> to actually read it.

Eg:

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; 
    }
  }
}

Use a file stream, read line by line and parse each line with a 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;
}

You'll need to include

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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