There are 3 BIG problems here.
- You are passing the vector by value, not by reference. As a result, any changes made to the vector in the function will stay local to the vector initialised as a part of that function call stack. It will be deleted by the time you return. so change the signature to
str_read(std::vector<char>& str)
.
- You are going through the
stdin
capture character by character. AFAIK scanf
although will read the new line character, will leave it in the buffer not appending it to your string. From the looks of it, all you are trying to do is read a string from stdin
, store it in a char array, and print that char array out. Don't overengineer stuff. just use std::cin
and store it in a string, to begin with, like
std::string captured_string;
std::getline(std::cin, captured_string);
You can then std:cout << captured_string << "\n";
directly
- If you insist on storing characters in a vector, which I do not understand why would you need to, you can just do
std::vector<uint8_t> char_array(captured_string.begin(), captured_string.end())
. However, std::cout << char_array << "\n"
will still not work. That is for 2 reasons, the first one being that std::vector<T, allocator>
does not have an overload for <<
of std::ostream
. The second is that the moment you convert your string to an array of characters, they do not mean the same thing.
I think you misunderstood what you were taught in class about strings being stored as arrays of characters. They are indeed stored as arrays, but an array type and a string type are fundamentally different and are not equivalent.
Capturing the string from stdin
will anyway store it in a char*
or a std::string
as I have shown above. You can use that directly without having to convert a string to an array of characters.
In essence, your program decays to this
#include <iostream>
#include <string>
int main()
{
std::string captured_string;
std::getline(std::cin, captured_string);
std::cout << captured_string << "\n";
return EXIT_SUCCESS;
}
EDIT
I just realised that your objective may have been to print the string character by character. In that case, you don't need to convert it to an array. There are multiple ways of doing this, but the least confusing and probably the easiest way of doing this would be to use the range-based for
loop.
int main()
{
std::string captured_string;
std::getline(std::cin, captured_string);
for (auto& ch: captured_string) // containers in the standard library support range based for loops.
std::cout << ch << "\n"; // print each character in the string on a new line
return EXIT_SUCCESS;
}