Reputation: 1
i am new into coding, and im trying to make a code that saves names, but when i run it, it only saves the first letter of the input, idk what i did wrong the languaje is cpp, and this is the code
#include <iostream>
using namespace std;
int main() {
int cv;
cout<<"Cuantas personas van a participar? "<< endl;
cin>> cv ;
char nombres[cv]{};
for(int x = 1; x<=cv; x++){
cin>>nombres[x];
cout<<nombres[x]<< endl;
}
return 0;
}
Upvotes: 0
Views: 403
Reputation: 25
#include <iostream>
using namespace std;
int main(){
int cv;
cout<<"Cuantas personas van a participar? "<< endl;
cin>> cv ;
char nombres[cv];
for(int x = 0; x<cv; x++){
cin>>nombres;
cout<<nombres<< endl;
}
return 0;}
This is a simple and easy approach for the same task. By using nombres instead of nombres[], we are inputting string as a whole without entering characters one by one.
In your given code, you are using 'int cv' as the string length as well as the termination condition of the for loop. Instead you can take two different integers for the respective tasks. Always try to start your 'for loop' with x=0 . By taking x=1 as initialization, nombres[0] is left blank and therefore can create errors.
Upvotes: 0
Reputation: 52
Just replace
char nombres[cv]{};
with
string nombres[cv]{};
Only first letter was getting stored because char stores only one character. String is used to store an array of characters (basically multiple characters)
Upvotes: 1
Reputation: 46
char data type only stores a single character. To store a sequence of characters, use string instead. Also, the index of an array starts from 0. Always start the for loop from 0.
#include<iostream>
#include<string>
using namespace std;
int main()
{
int cv;
cout<<"Cuantas personas van a participar? "<<endl;
cin >> cv;
string nombres[cv]{};
for(int x = 0;x < cv;x++)
{
cin >> nombres[x];
cout << nombres[x] << endl;
}
return 0;
}
Upvotes: 0
Reputation: 1
#include <iostream>
using namespace std;
int main() {
int cv;
cout << "Cuantas personas van a participar? "<< endl;
cin >> cv ;
string nombres[cv]{};
for(int x = 0; x< cv; x++){
cin >> nombres[x];
}
for(int y = 0; y< cv; y++){
cout << nombres[y] << endl;
}
return 0;
}
Hopefully this, helps, not sure if I correctly understood your question.
Upvotes: -1