1

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.

4

4 回答 4

7
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
}
于 2011-03-06T05:03:31.267 回答
1

@James McNellis 已经指出了基本问题。我的建议是:

  1. 不要使用getline.
  2. 不要在同一个语句中混用getline和。>>
  3. 使用循环。
于 2011-03-06T05:07:45.933 回答
0

我发现其他 C++ getline 使用起来更容易、更安全;

string str;
getline (cin,str);

将整行吞下并将其放入一个字符串中,然后您可以通过许多精细的字符串方法或 stringstream 播放,如果您想对部分字符串进行 I/O。

于 2011-03-06T05:10:50.787 回答
0

这是我选择做的,以确保我在使用时不会丢失任何单词或字母getline

cout << "\nEnter some words: ";

while (getline(cin,myString)){
       getline(cin,myString);
       break;
};
于 2021-04-01T13:29:20.290 回答