Reading String Input

How to Read String Input in C++

Learn how to read string input in C++ with std::cin and std::getline, handle leftover newlines, check stream state, and avoid unsafe gets() calls.

On this page
  1. The short answer
  2. Reading one word with cin
  3. Reading a whole line with getline
  4. Mixing cin >> and getline
  5. Checking that the read worked
  6. Reading words until the input ends
  7. Reading into a C-style char array
  8. Why not use gets()
  9. Common mistakes
  10. Quick recap

The short answer

Use std::cin >> text to read one word, up to the next space or line break. Use std::getline(std::cin, text) to read a whole line, including the spaces. Both need #include <iostream> and #include <string>, and the text goes into a std::string variable.

Reading one word with cin

#include <iostream>
#include <string>

int main() {
    std::string name;

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

    std::cout << "Hello, " << name << "!\n";
    return 0;
}

The >> operator skips any leading spaces, tabs, or line breaks, then reads characters until it reaches the next whitespace. If the user types Ada Lovelace, name holds only Ada. The rest of the line, Lovelace, stays in the input and a later >> can read it.

Reading a whole line with getline

#include <iostream>
#include <string>

int main() {
    std::string address;

    std::cout << "Enter your street address: ";
    std::getline(std::cin, address);

    std::cout << "You entered: " << address << "\n";
    return 0;
}

std::getline keeps reading until it reaches a newline, so spaces become part of the result. The newline ends the read and is not stored in the string. Use getline for sentences, addresses, or any input that can contain spaces.

Mixing cin >> and getline

This is the most common source of confusion. Suppose a program reads a number with >> and then reads a line with getline:

#include <iostream>
#include <string>

int main() {
    int age = 0;
    std::string city;

    std::cout << "Enter your age: ";
    std::cin >> age;

    std::cout << "Enter your city: ";
    std::getline(std::cin, city);  // returns an empty string right away

    std::cout << "City: '" << city << "'\n";
    return 0;
}

When the user types 25 and presses Enter, >> reads the 25 but leaves the newline behind. getline reads that leftover newline as an empty line, so city ends up empty and the program never waits for the user to type a city.

To fix this, discard the leftover newline before calling getline:

#include <iostream>
#include <limits>
#include <string>

int main() {
    int age = 0;
    std::string city;

    std::cout << "Enter your age: ";
    std::cin >> age;

    // Skip everything up to and including the leftover newline
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

    std::cout << "Enter your city: ";
    std::getline(std::cin, city);

    std::cout << "City: '" << city << "'\n";
    return 0;
}

std::numeric_limits is declared in <limits>. The call to ignore discards characters until it has removed the newline, so the next getline waits for real input.

Another option is to read every line with getline and convert the number yourself with std::stoi, which is declared in <string>. It throws an exception when the text is not a valid number, so wrap the call in a try block if the input may be bad.

Checking that the read worked

Input can end before your program expects it, for example when the user presses Ctrl+D on Linux or macOS, or Ctrl+Z and then Enter on Windows. A stream evaluates to false after a failed read, so test the result of the read itself:

#include <iostream>
#include <string>

int main() {
    std::string word;

    if (std::cin >> word) {
        std::cout << "You typed: " << word << "\n";
    } else {
        std::cout << "No input was read.\n";
    }
    return 0;
}

Checking the stream is good practice for any read. Without it, a failed read can leave your variable empty or unchanged, and the program keeps going as if nothing went wrong.

To check the input against a fixed answer such as yes, see how to compare two strings in c.

Reading words until the input ends

To read every word in the input, put the >> call in a loop. The loop stops when the read fails at the end of the input:

#include <iostream>
#include <string>

int main() {
    std::string word;
    int count = 0;

    while (std::cin >> word) {
        ++count;
    }

    std::cout << "Words read: " << count << "\n";
    return 0;
}

Run the program, type a few words, then send the end-of-input signal described above to finish. To join the words back into one string, see how to concatenate strings in c.

Reading into a C-style char array

Older code and some C-style interfaces use a fixed-size char array. You can read into one with std::cin.getline:

#include <iostream>

int main() {
    char buffer[32];

    std::cout << "Enter a short word: ";
    std::cin.getline(buffer, sizeof(buffer));

    std::cout << "You entered: " << buffer << "\n";
    return 0;
}

The function stores at most 31 characters and then adds the terminating zero. If the line is longer than the buffer, the rest stays in the input and the stream enters a failed state.

A fixed-size buffer means you must guess the longest input you will accept. For most programs, std::string is the simpler choice because it grows to fit the text.

Why not use gets()

Some older tutorials use gets() to read a line in C. It has no limit on how many characters it stores, so long input can overflow the buffer. The C standard removed it in C11, and C++14 removed it as well. In C, use fgets with a size limit. In C++, use std::getline.

Common mistakes

  • Expecting >> to read a full name. It stops at the first space, so use getline for names with spaces.
  • Forgetting to discard the newline that >> leaves behind before calling getline.
  • Reading input without checking whether the read succeeded.
  • Using a small char array with cin.getline and not planning for long lines.

Quick recap

Use std::cin >> text for one word and std::getline(std::cin, text) for a whole line. After mixing >> with getline, discard the leftover newline with cin.ignore. Check the stream after each read, and prefer std::string over fixed-size char arrays.

Keep exploring

Guides from other topics

All topics →

Heap vs Stack Memory in C++

Learn how heap and stack memory differ in C++: how each is allocated, how long data lives, the speed and size trade-offs, and common mistakes, with examples.

Heap vs Stack 5 min read

Is C++ Better Than C?

C++ grew out of C and adds classes, templates, and a large standard library. Neither is better in every case. See how they differ and which suits your goals.

C++ vs C 4 min read