Getline reading whole line and ignoring spaces.

Basically I'm reading a line from a file and putting the contents into a structure, my problem is that the file keeps reading the whole line together and ignoring the spaces, which I need to determine where each word is separated.

Here is my getline statement.

 
while((count < MAX_LINE) && ( !inFile.getline( itemLine, MAX_STRING, '\n' ).eof() ))


And here is the part that puts it insto the structure (it's in a different function).

1
2
3
4
5
6
7
8
        while ((itemLine[i] != NULL) && (itemLine[i] != ' '))
        {
            pArray[count].name[i] = itemLine[i];

            cout << pArray[count].name[3];

            i = i + 1;
        }


Everything is reading correctly other than that the whole line is put into pArray[count].name instead of just the first word.
Why do you use a function designed to read entire lines and then complain that it does its job correctly? If you don't want that behavior, don't ask it to read the entire line.
It's reading the line, but it's not reading the blank spaces. The file I'm reading looks like this:

Hammer 10 54.33
Nail 7 31.80

And when the second part executes it doesn't stop at a blank space or NULL and instead puts the whole line into the pArray[count].name.

EDIT: The spaces aren't really showing up, but just imagine there is several spaces after Hammer and Nail and after 10 and 7.
Last edited on
Your code specifically asks to read until a newline character, so of course it will read spaces just the same as anything else.
Then how come the spaces aren't put into their own elements?

itemLine looks like

Hammer1054.33

instead of

Hammer 10 54.33

Shouldn't the spaces be put into their own elements?
What do you think this code is doing? && (itemLine[i] != ' ')
It should be putting characters into pArray[count].name[i] as long as itemLine[i] isn't a NULL character and not a space.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>

struct tool
{
    std::string name ;
    int how_many ;
    double unit_price ;
};

int main()
{
    std::istringstream file( "Hammer 10 54.33\n" "Nail 7 31.80\n" "Gimlet 23 45.67\n" "Chisel 2 89.4\n" ) ;

    const int MAX_LINE = 100 ;
    int count = 0 ;
    tool array[MAX_LINE] {} ;

    std::string name ;
    int how_many ;
    double unit_price ;

    for( ; count < MAX_LINE && file >> name >> how_many >> unit_price ; ++count )
        array[count] = { name, how_many, unit_price };

    for( int i = 0 ; i < count ; ++i )
    {
        std::cout << i+1 << '.' << std::setw(8) << array[i].name << ' '
                  << std::setw(5) << array[i].how_many
                  << std::fixed << std::setprecision(2) << std::setw(6) << array[i].unit_price << '\n' ;
    }
}

http://coliru.stacked-crooked.com/a/8c588c7e9abb7e14
Topic archived. No new replies allowed.