0

I have two questions. I'm trying to read in line by line from a file but I can't get each line to go individually to where I can use it. Also, I can't figure out how to ask the user for their file name and than use what they type in the program. All the examples I've found just has the name of the file in the code already and just putting it in cin doesn't seem to work. I am trying to separate two different types of lines, so for example, abcd and 1234. If the first value is a letter do case a, if it's a number, do case b. But all I've managed to do is have getline have everything in one so I can't actually separate it. Anyone have any advise?

string x;
cout << "Enter your file: " ;
cin >> x
string line;
ifstream myfile;
myfile.open (x);
while(!myfile.eof())
{
    getline(myfile,line, ' ');
}
cout << line << endl;
Jen
  • 225
  • 3
  • 10
  • 2
    @πάνταῥεῖ I don't think this is a duplicate of that. He's not even clear about what the actual problem is anyway. – 0x499602D2 Feb 21 '14 at 20:21
  • 1
    @0x499602D2 Honestly, I've been searching for a dupe and couldn't find a really matching (high voted one). Though I'm pretty sure I've seen this same question/problem more than a 100 times since I'm participating SO. – πάντα ῥεῖ Feb 21 '14 at 20:24

2 Answers2

3

There is nothing wrong with your cin statement for reading the file name. As long as the file exists, what you have will open the file. Though, you can add some error checking to it:

std::string x;
std::cout << "Enter your file: " ;
if (!(std::cin >> x))
{
    std::cerr << "Invalid input!" << std::endl;
    return -1;
}

std::ifstream myfile(x);
if (myfile.is_open())
{
    std::string line;
    while (myfile >> line)
    {
        std::cout << line << std::endl;
    }
}
else
{
    std::cerr << "Unable to open file:  " << x << std::endl;
    return -1;
}

Note the proper while condition (do not use eof() for std::istream while conditions!). Additionally, if you are separating on whitespace, there is no need to use std::getline - operator>> will do the same thing.

If you want to do different things based on what the value of line is, then check the string. For example:

if (line[0] >= '0' && line[0] <= '9')
    // do something with digits
else
    // do something with non-digits
Zac Howland
  • 15,149
  • 1
  • 23
  • 37
1

First, don't put eof() in while condition. It's wrong because iostream::eof will only be set after reading the end of the stream. It does not indicate, that the next read will be the end of the stream. Check out this post: Why is iostream::eof inside a loop condition considered wrong?

To separate, you can check the first char of the line is whether within ['0', '9'] or not.

Like this:

while( getline(myfile, line) )
{
    if (line[0]>='0' && line[0]<='9')
    {
        // start with a number (do case b)
    }
    else
    {
        // other (do case a)
    }
}
Community
  • 1
  • 1
herohuyongtao
  • 45,575
  • 23
  • 118
  • 159