In C++, there are several ways to include spaces in string values. Here are the most common methods:
#include <iostream>
#include <string>
using namespace std;
int main() {
// Method 1: Direct assignment with spaces
string str1 = "Hello World";
cout << str1 << endl;
// Method 2: Multiple spaces
string str2 = "Hello World";
cout << str2 << endl;
// Method 3: Spaces at beginning and end
string str3 = " Hello World ";
cout << str3 << endl;
return 0;
}
#include <iostream>
#include <string>
using namespace std;
int main() {
// Using escape sequences (though not necessary for regular spaces)
string str1 = "Hello\tWorld"; // Tab space
string str2 = "Hello\nWorld"; // New line
string str3 = "Hello\\ World"; // Backslash followed by space
cout << str1 << endl;
cout << str2 << endl;
cout << str3 << endl;
return 0;
}
#include <iostream>
#include <string>
using namespace std;
int main() {
string firstName = "John";
string lastName = "Doe";
// Method 1: Using + operator with space string
string fullName1 = firstName + " " + lastName;
cout << fullName1 << endl;
// Method 2: Using append() function
string fullName2 = firstName;
fullName2.append(" ");
fullName2.append(lastName);
cout << fullName2 << endl;
return 0;
}
#include <iostream>
#include <string>
using namespace std;
int main() {
string userInput;
cout << "Enter a string with spaces: ";
// Method 1: Using getline() - reads entire line including spaces
getline(cin, userInput);
cout << "You entered: " << userInput << endl;
// Method 2: Using cin - stops at first space
cout << "Enter another string: ";
cin >> userInput; // This will only read until first space
cout << "You entered: " << userInput << endl;
return 0;
}
#include <iostream>
#include <cstring>
using namespace std;
int main() {
// Character arrays with spaces
char str1[] = "Hello World";
char str2[50] = "C++ Programming Language";
cout << str1 << endl;
cout << str2 << endl;
// Using strcpy with spaces
char str3[50];
strcpy(str3, "This has spaces");
cout << str3 << endl;
return 0;
}