Home > Software engineering >  cout operator << doesn't work for vector<char>
cout operator << doesn't work for vector<char>

Time:12-17

Why doesn't this vector print out?

 void str_read(std::vector<char> str);

 int main() {
     std::vector<char> str;
     str_read(str);
     std::cout << str << std::endl;

     return -1;
 }

 void str_read(std::vector<char> str) {
     while (1) {
         char ch;
         scanf("%c", &ch);
         if (ch == '\n');
         break;
     }   
 }

I get an error:

error: no type named 'type' in 'struct std::enable_if<false, void>'

CodePudding user response:

There are 2 BIG problems here.

  • 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::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::cin >> captured_string;
  std::cout << captured_string << "\n";
  return EXIT_SUCCESS;
}

CodePudding user response:

Your 'str' variable doesn't have anything in it when you try to display it. You also don't initialize your vector to any variables for the function to read anyways.

  • Related