Welcome to HBH! If you have tried to register and didn't get a verification email, please using the following link to resend the verification email.
C++ variable containing spaces
Hi!
I'm writing an application which takes user input and stores it in an array of chars. But how can I make it store spaces? Like if the user types "Hello World" (without quotes) the variable will contain "Hello World", not just "Hello" and the next time it's called it automatically fills in "World"?
I've also tried using a string to store the data, but without success.
I hope you understand what I mean… :p
Peace B)
If you're working from a command line sort of prompt:
#include <cstdlib>
#include <iostream>
#include <string.h>
using namespace std;
string input;
int main(int argc, char *argv[])
{
cout<<"Type a string\n";
std::getline(std::cin, input); // Delimits at the '/n/r' (Enter Key) instead of a space
cout<<input<<endl;
system("PAUSE"); // Remove if not on WinXP
return 0;
}
It's not the prettiest code, but I just woke up 20 minutes ago. Enjoy.
#include <string>
using namespace std;
int main()
{
cout << "Enter your name: ";
string name;
getline(cin,name);
cout << "\nYour name is " << name << endl;
system("pause");
return 0;
}```
or you can put.....
```markup#include <iostream>
#include <string.h>
using namespace std;
int main()
{
cout << "What is your name?\n";
char name[40];
cin.getline(name,39); //39 because we need 1 byte for the terminating byte
cout << "Your name is " << name << endl;
system("pause");
return 0;
}