Input String in C++: Best Methods Explained

In C++, there are several ways to input strings.

  1. Use cin for input: The cin object can be used to input strings, but it will stop at spaces, so it is not suitable for inputting strings containing spaces.
#include <iostream>
#include <string>
using namespace std;

int main() {
    string str;
    cout << "Enter a string: ";
    cin >> str;
    cout << "You entered: " << str << endl;
    return 0;
}
  1. You can use getline to input: The getline function allows you to input strings, including those with spaces.
#include <iostream>
#include <string>
using namespace std;

int main() {
    string str;
    cout << "Enter a string: ";
    getline(cin, str);
    cout << "You entered: " << str << endl;
    return 0;
}
  1. You can input using scanf: You can input strings using the scanf function, but you need to specify the formatting string “%s”.
#include <cstdio>

int main() {
    char str[100];
    printf("Enter a string: ");
    scanf("%s", str);
    printf("You entered: %s\n", str);
    return 0;
}

These are common ways to input strings in C++, you can choose the suitable one according to your actual needs.

bannerAds