0
0
C++programming~5 mins

String input and output in C++

Choose your learning style9 modes available
Introduction

We use string input and output to read words or sentences from the user and show text on the screen.

When you want the user to type their name.
When you need to get a sentence or phrase from the user.
When you want to display messages or results as text.
When you want to ask questions and get answers in words.
When you want to show instructions or information on the screen.
Syntax
C++
#include <iostream>
#include <string>

int main() {
    std::string text;
    std::getline(std::cin, text); // to read a full line including spaces
    std::cout << text << std::endl; // to print the string
    return 0;
}

Use std::getline(std::cin, variable) to read a whole line including spaces.

Use std::cin >> variable to read a single word (stops at space).

Examples
This reads one word (no spaces) and greets the user.
C++
#include <iostream>
#include <string>

int main() {
    std::string name;
    std::cin >> name;
    std::cout << "Hello, " << name << "!" << std::endl;
    return 0;
}
This reads a full line including spaces and prints it back.
C++
#include <iostream>
#include <string>

int main() {
    std::string sentence;
    std::getline(std::cin, sentence);
    std::cout << "You wrote: " << sentence << std::endl;
    return 0;
}
Sample Program

This program asks the user to enter their full name (including spaces) and then greets them by name.

C++
#include <iostream>
#include <string>

int main() {
    std::cout << "Enter your full name: ";
    std::string fullName;
    std::getline(std::cin, fullName);
    std::cout << "Welcome, " << fullName << "!" << std::endl;
    return 0;
}
OutputSuccess
Important Notes

Remember to include <string> to use the std::string type.

Using std::getline is best when you want to read sentences or names with spaces.

Using std::cin >> reads only up to the first space.

Summary

Use std::string to store text.

Use std::getline(std::cin, variable) to read full lines with spaces.

Use std::cout to print strings to the screen.