Search code examples
c++spacepunctuation

How to read in file containing blank space and punctuation?


I have problem reading in the file that contain space ad punctuation. I use inFile >> letter to read the char and num. When I read file that is space or punctuation, it stop reading the text file.

Here's the text file I need to read

a 31
  12
e 19
i 33
o 41
u 11
, 2

Code:

char letter; 
int num; 

inFile.open(FILENAME.c_str());
  if(inFile.fail())
    cout << "Error..." << endl;
  while (inFile >> letter){
    inFile >> num ;
  }
  inFile.close();

Could anyone tell me how to fix it?

Thanks


Solution

  • I've compiled this code(MSVC2012):

    char letter; 
    int num; 
    std::fstream inFile;
    
    inFile.open("1.txt");
    if(inFile.fail())
    {
        cout << "Error..." << endl;
    }
    while (inFile >> letter)
    {
        inFile >> num ;
        std::cout << letter << " | " << num << std::endl;
    }
    inFile.close();
    

    And get this output:

    a | 31
    1 | 2
    e | 19
    i | 33
    o | 41
    u | 11
    , | 2
    

    If you have another compiler and it stops parsing, you can use std::getline and try use std::stringstream:

    char letter; 
    int num; 
    std::fstream inFile;
    
    inFile.open("1.txt");
    if(inFile.fail())
    {
        cout << "Error..." << endl;
    }
    while (!inFile.eof())
    {
        std::string line;
        std::getline(inFile, line);
        std::stringstream stream(line);
        stream >> letter >> num;
        std::cout << letter << " | " << num << std::endl;
    }
    inFile.close();
    

    But you still get the problem if you have a space in the begining of string. To avoid this, you should split string by spaces and parse the parts by stringstream or atoi