Click here to Skip to main content
15,902,635 members
Please Sign up or sign in to vote.
2.60/5 (2 votes)
See more:
i writed this code in vs 2010 for get students id and full name and then print them,but it doesn't work again
i need your advise
please help me
#include <iostream>
#include<string>
using namespace std;
int main(){
string str[100];
int ID[100],i,count;
cout<<"enter number of students:";
cin>>count;
for (i=0;i<count;i++){
	cout<<"\nenter student id:";
	cin>>ID[i];
	cout<<"\nenter student full name:";
	getline(cin,str[i]);
}
cout<<endl;
for(i=0;i<count;i++){
cout<<i+1<<"\t"<<ID[i]<<"\t"<<str[i].data();
}

return 0;
}
Posted
Updated 21-Apr-11 0:19am
v3
Comments
Himansu sekhar bal 21-Apr-11 4:44am    
what is cin>>sum.i do not understand
[no name] 21-Apr-11 4:56am    
Is code gives compliler error
CPallini 21-Apr-11 6:05am    
The posted code don't give compiler errors, however, it doesn't work properly (cin issues, moreover it doesn't check for array bounds violations).

1 solution

Declare your variables properly:
string str[100];
int sum;
cin >> sum;
if (sum >= 100) // Watch out for buffer overflow
	sum = 100;
int count=0;
while (count < sum)
{
	getline(cin,str[count]);
	count++;
}
for (int i=0; i < sum; i++)
	cout << str[i] << endl;
 
Share this answer
 
v2
Comments
CPallini 21-Apr-11 5:27am    
Check properly array bounds, man. :-D
However, get my 5.
Niklas L 21-Apr-11 5:35am    
I don't know what you are talking about :rolleyes:
CPallini 21-Apr-11 5:41am    
Should be:
if (sum >= 100) sum=99;
Niklas L 21-Apr-11 6:26am    
Then the index won't be higher than 98.
<font='tiny and white'>I changed the loop conditions before writing my comment above</font>
CPallini 21-Apr-11 6:33am    
Well, you fixed it 'the other way' making my remark pointless.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900