patterncppMinor
Printing out vector<string> char by char
Viewed 0 times
charprintingstringoutvector
Problem
I have learned a bit of C in university and I'm now learning C++ independently. I'm trying to print out
This works, but I'm unsure if it's the correct way to do this. I know, I can use
std::vector char by char. I know, that in C, strings are arrays and are terminated by '\0' terminator. Can I assume the same thing in c++? I use C++14.This works, but I'm unsure if it's the correct way to do this. I know, I can use
getline(std::cin, line) to read from stream as well. Which one is more preferred? How would you make my code better?using namespace std;
int main()
{
cout str;
for (string temp; cin >> temp; ) {
str.push_back(temp);
// If input ends with enter, break loop
if (cin.peek() == '\n') break;
}
cout ::iterator it;
for (it = str.begin(); it != str.end(); ++it) {
cout '\0 terminated? */
for (size_t i = 0; (*it)[i] != '\0' ; ++i) {
cout << (*it)[i];
}
cout << ' ';
++it;
}
cout << "\n\n";
}Solution
So the first thing you can do is to use container loops
The second thing would be to have a look at rbegin() and rend, which give you reverse_iterators.
You can find a very good reference here: http://www.cplusplus.com/reference/string/string/rend/
Together you would get something like that
for (std::string &mystring : str) {
// do someting
}The second thing would be to have a look at rbegin() and rend, which give you reverse_iterators.
You can find a very good reference here: http://www.cplusplus.com/reference/string/string/rend/
Together you would get something like that
for (std::string &mystring : str) {
for (std::string::reverse_iterator rit=mystring.rbegin(); rit!=mystring.rend(); ++rit) {
std::cout << *rit;
}
}Code Snippets
for (std::string &mystring : str) {
// do someting
}for (std::string &mystring : str) {
for (std::string::reverse_iterator rit=mystring.rbegin(); rit!=mystring.rend(); ++rit) {
std::cout << *rit;
}
}Context
StackExchange Code Review Q#139841, answer score: 6
Revisions (0)
No revisions yet.