简体   繁体   中英

Why is cin.getline() skipping the first word in each line?

I am trying to display the text of a command line inputted text file line by line. But for some reason, it skips the first word in each line after the first line.

code:

using std::cout;  
using std::cin;  
using std::endl;  

int main (int args, char* argv[])  
{   
 char x[100];  
 char y[100];  
 char z[100];  
 cin.getline(x,100) >> argv[2];  
 cin.getline(y,100) >> argv[2];  
 cin.getline(z,100) >> argv[2];  
 cout << x <<endl;  
 cout << y <<endl;  
 cout << z <<endl;  
 return 1;  
}  

running ./a.out < moby.txt displays this:

CHAPTER 1. Loomings. 

me Ishmael. Some years ago--never mind how long precisely--having  
or no money in my purse, and nothing particular to interest me on

but the first three lines in moby.txt is this:

CHAPTER 1. Loomings.

Call me Ishmael. Some years ago--never mind how long precisely--having  
little or no money in my purse, and nothing particular to interest me on

The code is omitting "Call" and "little".
I feel like this is an \\n error but i have no idea how to fix it. Thanks in advance for any help.

cin.getline(x,100) >> argv[2];

You read a line (or the first 99 characters of the line) into x . Then you skip any whitespace and read the next word into argv[2] . The first words are ending up there.

Why are you using >> argv[2] ? What are you possibly trying to do with this? argv[2] may not exist and even if it does, you don't have any control over the size of the character array pointed to by argv[2] , so your chances of overrunning that array are quite high.

Rather than using char arrays directly for this, use std::getline with std::string to read lines into std::string objects: it is much easier to write correct code this way. For example,

std::string x;
if (!std::getline(std::cin, x)) {
    // handle input error
}

@James McNellis has already pointed to the basic problem. My advice would be:

  1. Don't use the member-function form of getline .
  2. Don't mix getline and >> in the same statement.
  3. Use a loop.

I find the other C++ getline to be easier and safer to use;

string str;
getline (cin,str);

will slurp the entire line and put it into a string, which you can then play with via the many fine string methods, or stringstream if you want to do I/O on parts of the string.

This is what I chose to do to make sure I am not missing any words or letters when I Use getline :

cout << "\nEnter some words: ";

while (getline(cin,myString)){
       getline(cin,myString);
       break;
};

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