DatapawWolf
DatapawWolf

Reputation: 81

Reading TXT Lines into Character

I'm completely out of ideas right now. Basically, I want to read parts of a line in a text file, but this code is not working, and I have no idea why:

        char temp_char  = '\0';
        char _char = '\0';
        while(1)
        {
            _places.get(temp_char);
            if(temp_char == '\t')
                break;

            _char += temp_char;

            cout << _char;
        }

Basically, it's supposed to read from the start of the file until it comes into contact with a tab character. Unfortunately, it never stops, and _char comes out as a ton of random characters that make no sense.

I've looked over the TXT file, and it's the correct encoding and all, and the tab is a normal tab character in the file, but for whatever reason I can't read it from the stream using either get or >>.

I've been experimenting for an hour now, looked over numerous websites for help, and I've gotten nowhere... all this is doing is stressing me out...

Edit: I can also provide the rest of the program code if this isn't the problem, but it should be. :/

Here is where the file is opened:

                ifstream _places;
                _places.open("ECC.txt");
                if (_places.fail())
                {
                    cout << "Could not load text file, please make sure ECC.txt is in the same folder.";
                    _getch();
                    exit(1);
                }

Upvotes: 2

Views: 109

Answers (1)

Martol1ni
Martol1ni

Reputation: 4702

First, is _char a std::string, char[] or a char* ?

Secondly, I would have used either

temp_char = _places.get()

or

std::string temp;
getline(_places,temp)
for (unsigned int i=0; i<temp.size(), ++i)
    if (temp[i] == '\t')
        break;
    _char += temp[i] // assuming, and REALLY HOPING _char is a std::string 

Be careful with the get() methods from the ifstream, when they can return the int.

Upvotes: 2

Related Questions