iostream string

why doesn't work the following code?( I want to use char and not the class string)

1
2
3
4
5
6
7
8
9
#include <iostream>
using namespace std;

int main(){
char *a;
cout<<"insert name"<<endl;
cin>>a;
cout<<a<<endl;
return 0;


}
Last edited on
1
2
3
4
5
6
7
8
9
10
11
#include <iostream>

int main()
{
   char a { };

   std::cout << "insert a letter: ";
   std::cin >> a;

   std::cout << "\nYou entered " << a << '\n';
}

insert a letter: w

You entered w
If you want a C-style string (char array):

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>

int main()
{
   char a[20];

   std::cout << "Enter your name: ";
   std::cin >> a;

   std::cout << "\nYou entered " << a << '\n';
}

Enter your name: Mork

You entered Mork


A C-style string on the heap:
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>

int main()
{
   char* a = new char[20];

   std::cout << "Enter your name: ";
   std::cin.getline(a, 20);

   std::cout << "\nYou entered " << a << '\n';

   delete[] a;
}

Enter your name: Mindy

You entered Mindy
Since no-one's actually bothered to answer your question:

why doesn't work the following code?

... I'll do that.

It doesn't work, because you haven't initialised a. The value of a is undefined, which means you have no idea what memory it's pointing to. It could be NULL, or it could be a random block of memory that's being used for something else.

On line 7, when you try to write data to the memory a is pointing to, you have undefined behaviour - most likely, your program crashes.

What you need is to have a point to some memory you've allocated to hold the string. Furry Guy has shown you how to do this.

By the way, "doesn't work" is a pretty useless problem description. You should give us a clear, precise and complete description of the behaviour you're seeing, and how it differs from the behaviour you expect.
Last edited on
1
2
3
   char a[20];
   ...
   std::cin >> a;
This is fixed in C++20, but until that comes out, it's as bad as gets(a); was. Either std::cin >> std::setw(20) >> a; or std::cin.getline(a, 20);
Last edited on
@Cubbi, I don't agree that is a defect, just a more "relaxed" way to do input, but the change will help make it easier to understand a C string is being retrieved.

I also used std::cin::getline, as a personal learning experiment, after posting the code for the C string on the stack above. I will use it from now on even without C++20 to get a C string. Not matter what the stream might be.
Topic archived. No new replies allowed.