array and string basic question
Hi all,
I am trying to learn the basic concept about array, however when I tried to change the type into string, it shows error .. I am using IDE visual studio 2005
#include <iostream>
#include <string>
using namespace std;
int main()
{
string stName[20];
cout << "what is your name? " << endl;
cin >> stName;
cout << stName << endl;
}
Thanks for the assistance..
reza.adinata
Junior Poster in Training
54 posts since Nov 2009
Reputation Points: 10
Solved Threads: 0
In order to place the string into the array of strings you must specify an index. E.g.,
cin >> stName[0]; //to write into the first string in the array
cout<<stName[0]<<endl;
jonsca
Quantitative Phrenologist
5,621 posts since Sep 2009
Reputation Points: 1,165
Solved Threads: 581
In order to place the string into the array of strings you must specify an index. E.g.,
cin >> stName[0]; //to write into the first string in the array
cout<<stName[0]<<endl;
But the question is that, how to show output of all inputs within the array? not just each element.. Example, I want to type " MY NAME" and i will get the result of " MY NAME ". I tried to use char, and it ends up showing only "MY"
thank you..
reza.adinata
Junior Poster in Training
54 posts since Nov 2009
Reputation Points: 10
Solved Threads: 0
But the question is that, how to show output of all inputs within the array? not just each element.. Example, I want to type " MY NAME" and i will get the result of " MY NAME ". I tried to use char, and it ends up showing only "MY"
thank you..
The >> operator treats a space as a delimiter, so it'll stop after the first name. Use getline to get a whole line(first and last name.
See the example on this link. It does exactly what you are trying to do. http://www.cplusplus.com/reference/string/getline/
As far as I can tell, you only need one string, not 20. You're only storing one name.
VernonDozier
Posting Expert
5,527 posts since Jan 2008
Reputation Points: 2,633
Solved Threads: 711
The >> operator treats a space as a delimiter, so it'll stop after the first name. Use getline to get a whole line(first and last name.
See the example on this link. It does exactly what you are trying to do.
http://www.cplusplus.com/reference/string/getline/
As far as I can tell, you only need one string, not 20. You're only storing one name.
I see.. yes, it is all clear. Thank you
reza.adinata
Junior Poster in Training
54 posts since Nov 2009
Reputation Points: 10
Solved Threads: 0