I am in some troubles with this part. According to the book, I can read and store data in a two-dimensional array of characters. Here is the example from the book:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#include<iostream>
#include<cstring>
usingnamespace std;
int main()
{
int i;
char list[5][16];
cout<<"Enter five names: "<<endl;
for (i=0; i<5; i++) //This loop read and store data in list and that there is one entry per line.
cin.get(list[i],16);
for (i=0; i<5; i++) //This loop outputs the string in each row
cout<<list[i]<<endl;
return 0;
}
However when I run this code, after entering first name, the program terminates and just outputs that name. Furthermore, the book indicates that this statement strcpy(list[1], "Snow white"; stores "Snow white" in list[1]. But when I run, the screen show a lot of strange symbols. I have no idea whether the book or my complier has errors. I use Dev C++.
I am a beginner in C++ too. I don't know about the strcpy() function, but by replacing it with gets() and adding the header cstdio, the following code works.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#include<iostream>
#include<cstring>
#include<cstdio>
usingnamespace std;
int main()
{
int i;
char list[5][16];
cout<<"Enter five names: "<<endl;
for (i=0; i<5; i++) //This loop read and store data in list and that there is one entry per line.
gets(list[i]);
for (i=0; i<5; i++) //This loop outputs the string in each row
cout<<list[i]<<endl;
return 0;
}
Never use gets(). Because it is impossible to tell without knowing the data in advance how many characters gets() will read, and because gets() will continue to store characters past the end of the buffer, it is extremely dangerous to use. It has been used to break computer security.
The delimiting character is not extracted from the input sequence if found, and remains there as the next character to be extracted from the stream (see getline for an alternative that does discard the delimiting character).
when everything else fails, RTFM.
> strcpy(list[1], "Snow white"); stores "Snow white" in list[1].
> But when I run, the screen show a lot of strange symbols.
create a minimal example that does reproduce your issue
> Never use gets(). Because it is impossible to tell ...
Because gets() is no longer part of portable C (deprecated by C99, and removed in C11).
Because std::gets() is no longer part of portable C++ (deprecated by C++11, and removed in C++14).