Good day! When parsing pointers in C, I encountered one problem:

#include <iostream> #include <cstdlib> #include <cmath> #include <cstdio> using namespace std; int main () { char* str1 = NULL; str1 = (char*)malloc(sizeof(char) * 20); cin >> *str1; for (int i = 0; i < 20; i++) cout << str1[i]; } 

When you enter any characters, then only the first character of the line is the same when outputting, everything else is displayed not what was entered (some kind of nonsense is output)!

I understand that everything can be done 987654 times easier, but I want to deal with this case.

How to make it so that the char string is displayed normally?

  • five
    And where did you get the cin in C? - PaulD
  • if you try to write the same code using printf, nothing will change - hamsternik
  • one
    How not to rewrite the code, in C neither cin nor cstdlib nor the namespace std will appear. This means that (1) you use a compiler that supports both (MSVC?), And (2) do not know the difference between these languages. - VladD pm
  • in c ++ I encountered a similar problem only in the code I used setlocale after I cleaned everything up perfectly - user206152

1 answer 1

No need to redirect str1 . When you pass to istream::operator>>() not a pointer to char , but char , istream assumes that you want to read only one value of this type.

Docks for operator overloads >> in istream :

  • Well, that's why I bring everything in a cycle, character by character. Is not it so? - hamsternik
  • Bring out all of you, and enter only the first element. - fori1ton
  • one
    I explain for @Hamsternik cin >> * str1; means entering one character at address str1 [0]. - alexlz
  • @ fori1ton: ideologically, you should use scanf for C, and readline and std::string for C ++. - VladD