+ 5

[SOLVED] vector::push_back() does not work.

Hey guys, I'm a little confused here. Why doesn't my code add elements to the vector? He is a relevant part of my code: std::vector<std::string> arr; std::string command = ""; std::getline(std::cin, command); bool check = false; std::string nStr = ""; // go trough all elements for(int i = 0; i < command.length(); i++){ // if current element is space or its the last // element, add a word to the array. if(((command[i] == ' ') || (i == command.length()-1)) && check){ arr.push_back(nStr); nStr = ""; check = false; } // else, add current character to the word else{ check = true; nStr+=i; } } std::cout << arr[0]; What I'm trying to do here, is basically take the string from the user and then divide it into words and add each word to the vector "arr", however at the end of my code arr still appears empty. I think that might be because I used getline() before, but I am not so sure. Could you please help me?

5th Oct 2021, 11:09 AM
Aleksei Radchenkov
Aleksei Radchenkov - avatar
10 odpowiedzi
+ 8
You are not adding the current character to the word, but the current index, hence the blank output in many cases (the ASCII characters in the range [0, 32] have no graphical representation). It should probably be nStr += command[i]; in the else statement.
5th Oct 2021, 11:54 AM
Shadow
Shadow - avatar
+ 2
I think, You are trying to add only when command[I]==' ' (space) so vector has only spaces as values....
5th Oct 2021, 11:35 AM
Jayakrishna 🇮🇳
+ 1
Use nStr=nStr+command[i]; instead of nStr+=I;
5th Oct 2021, 11:59 AM
Jayakrishna 🇮🇳
+ 1
Shadow, Jayakrishna🇮🇳 , Thanks a lot guys!
5th Oct 2021, 12:00 PM
Aleksei Radchenkov
Aleksei Radchenkov - avatar
+ 1
The noob's way 😂 while( std::cin >> command ) { arr.push_back( command ); std::cout << arr.back(); }
5th Oct 2021, 1:47 PM
Ipang
+ 1
Ipang, yuh but it won't work anywhere except sololearn... As it will ask for a new input each time... But thanks anyways! 😉
5th Oct 2021, 1:53 PM
Aleksei Radchenkov
Aleksei Radchenkov - avatar
+ 1
Yeah that's why it's noob's way LOL 😁
5th Oct 2021, 1:55 PM
Ipang
+ 1
Ipang, true 😂
5th Oct 2021, 1:56 PM
Aleksei Radchenkov
Aleksei Radchenkov - avatar
0
And I do realise there are a thousand better ways to achieve that, but I am interested in that specific way, and why that doesn't seem to work. Thank you in advance.
5th Oct 2021, 11:21 AM
Aleksei Radchenkov
Aleksei Radchenkov - avatar
0
Jayakrishna🇮🇳 , Thanks for your answer! I add nStr to the array every time char is ' ', as indication of end of the word, however I add characters to the nStr only when character is not a white space. Also it doesn't even output white space. It outputs nothing ("" )
5th Oct 2021, 11:39 AM
Aleksei Radchenkov
Aleksei Radchenkov - avatar