Hi. I'm new to this forum aswell as C++ programming. I started learning a few days ago and now I'm trying to make a program that gets a string the user inputs and then writes that string character by character. So far I've come up with the code below but it doesn't work for some reason.
A suggestion is to instead of using a array at all you can just step through the string.
For example.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include <iostream>
#include <string>
usingnamespace std;
int main()
{
string stuff;
cin >> stuff;
// Steps through the string and prints each char on a separate line.
for (string::size_type i = 0; i != stuff.size(); ++i)
cout << stuff[i] << endl;
return 0;
}
This code steps through the string and prints each character in the string on a separate line. You can modify it to fit your needs better if you need to.
Remember that a string is basically just a container that hold a bunch of characters. If we think about a string this way we realize that we can use it just like a array or vector in some cases.
Hope this helps a bit, and if there is anything you don't understand or need me to go into more detail on just let me know and I will do my best to try and help explain it.
If that's the case, you can't do that because arrays declared like that must have their dimension known at compile time. To get around this you could use pointers. As I'm not so good as those, I couldn't really explain how to.
If he wants to save the characters he can use a vector<char> to save them in. Though I'm not sure he wanted to save them since he wasn't in his original post. But just in case you do want to save each character from the string here is how you can do that.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
string name("brandon");
vector<char> letters;
for (string::size_type i = 0; i != name.size(); ++i)
{
// Prints the letters
cout << name[i] << endl;
// Stores each letter in the vector. Each element will contain a letter.
letters.push_back(name[i]);
}
// Prints each element in the vector
for (vector<char>::size_type i = 0; i != letters.size(); ++i)
cout << letters[i];
There is also other ways to do this but this is probably the easiest way to do so.