Providing Services to
World Wide

Mail Us
khizarshahal3@gmail.com

Contact Us
+92 3472506073

Answers

Home / Query Hub / Answers

How to write space in string value using C++

109 Views
1 Answers
Posted on 03 Oct 2025
how to write space in string c++
Submit Your Answer

Answers (1)

Answer #1
03 Oct 2025 16:52

In C++, there are several ways to include spaces in string values. Here are the most common methods:

1. Using Double Quotes with Spaces

#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;
}

2. Using Escape Sequences

#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;
}

3. Concatenating Strings with Spaces

#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;
}

4. Reading Strings with Spaces from Input

#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;
}

5. Working with Character Arrays (C-style strings)

#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;
}