Dec 18, 2011 at 2:33pm UTC
i am trying to loop this three times and get a long string with a space in between. however the program stops whenever i try to key in the third info....why???
#include <iostream>
using namespace std;
int main ()
{
string str[3];
for (int i=1; i<=3; i++)
{
cout<<"please enter your name : ";
getline (cin, str[i]);
}
for (int i=1; i<=3; i++)
{
cout<<str[i].substr(0,7)<<endl;
}
system ("pause");
return 0;
}
Dec 18, 2011 at 2:55pm UTC
@LEE PEI TING
The reason, is because arrays start at 0, not 1. Change your for loop to for (int i=0;i<3;i++)
and things should work out fine.
Dec 18, 2011 at 3:22pm UTC
oh...ok... thanks for that =)))
i was actually trying to use the getline
i apply on the code below but i did not get any output for it (name)... why???
#include <iostream>
#include <string>
using namespace std;
int main ()
{
int id;
int quantity;
double price;
string name;
cout << "ID : ";
cin >> id;
cout << "ITEM : ";
getline (cin, name);
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "PRICE : ";
cin >> price;
cout << "QUANTITY : ";
cin >> quantity;
cout <<id<<'\t'<<name<<'\t'<<price<<'\t'<<quantity<< endl<<endl;
system ("pause");
return 0;
}
Dec 18, 2011 at 3:48pm UTC
what if i wanted to use string and not char?
Dec 18, 2011 at 3:59pm UTC
yea.. that is what i'm doing there but i couldn't get the output =(
Dec 18, 2011 at 4:07pm UTC
what does ' std:: ' means?
Dec 18, 2011 at 4:26pm UTC
Well, actually, a string is just a group of chars.
Dec 18, 2011 at 7:31pm UTC
OK... i've got the solution =)))
should place cin.ignore()
before getline(cin,name)
@whitenite1 AND @Moschops,
thanks a lot for answering my silly question.
Merry Christmas in advance! =)