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.
You read a line (or the first 99 characters of the line) into
x. Then you skip any whitespace and read the next word intoargv[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 byargv[2], so your chances of overrunning that array are quite high.Rather than using
chararrays directly for this, usestd::getlinewithstd::stringto read lines intostd::stringobjects: it is much easier to write correct code this way. For example,