+ 1
Vector input fill?
https://code.sololearn.com/cO1Tdr5in85S/#cpp So i'm simply trying to fill a vector with integers via user input. How can I make this work properly? I want the vector contents to be ints rather than strings. And I can't seem to get multi-digit numbers to work either. I want the input to be numbers separated by commas. I just can't get it to work properly.
3 Respostas
+ 1
You should create some variable, n for example, that is responsible for the current number
If i points to a digit (s[i] >= '0' && s[i] <= '9'), than n = n * 10 + s[i] - '0';
If i points on a comma, then add n to the vector and then make n = 0
Or, more simpe way to do it, ask user for number of digits and get numbers with a for loop(for(int i =0;i<len;i++){cin>>x;vect.push_back(x))
This way, you can avoid using string
+ 1
Can you give me an example? I can't figure it out. If not, I'll just experiment tomorrow.
0
Firs method:
getline(cin,s);
For(int i=0;i<s.size();i++){
If(s[i]>='0' && s[i]<='9'){
n=n*10+s[i]-'0';
}
If(s[i]==','){
Vect.push_back(n);
n=0;
}
}
Second method:
cin>>n;
For(int i =0;i<n;i++){
Int x;
Cin>>x;
Vect.push_back(x);
}