How can I read a string with scanf() in C++?

25,846

Solution 1

Using the C scanf() function requires using C strings. This example uses a temporary C string tmp, then copies the data into the destination std::string.

char tmp[101];
scanf("%100s", tmp);
s[i][j] = tmp;

Solution 2

You can't, at least not directly. The scanf() function is a C function, it does not know about std::string (or classes) unless you include .

Solution 3

Not sure why you need to use scanf and Greg already covered how. But, you could make use of vector instead of a regular string array.

Here's an example of using a vector that also uses scanf (with C++0x range-based for loops):

#include <string>
#include <vector>
#include <cstdio>
using namespace std;

int main() {
    vector<vector<string>> v(20, vector<string>(5, string(101, '\0')));
    for (auto& row: v) {
        for (auto& col: row) {
            scanf("%100s", &col[0]);
            col.resize(col.find('\0'));
        }
    }
}

But, that assumes you want to fill in all elements in order from input from the user, which is different than your example.

Also, getline(cin, some_string) if often a lot nicer than cin >> or scanf(), depending on what you want to do.

Share:
25,846
Elmi Ahmadov
Author by

Elmi Ahmadov

Google Fan

Updated on July 12, 2022

Comments

  • Elmi Ahmadov
    Elmi Ahmadov almost 2 years

    I can read a string with std::cin but I don't know how to read with one withscanf(). How can I change the code below to use scanf() ?

    string s[20][5];
    
    for (int i=1;i<=10;i++)
    {
      for (int j=1;j<=3;j++) 
      {
          cin>>s[i][j];
      }
    }
    
  • Hải Phong
    Hải Phong over 11 years
    noob question: if you use "%100s" , what will it store when you enter a string less than 100 characters? (because it is told to store 100 characters)
  • Greg Hewgill
    Greg Hewgill over 11 years
    @HaiPhong: tmp will contain the contents of the string entered. The %100s means a maximum of 100 characters will be stored (plus the NUL terminator).
  • Bob__
    Bob__ over 5 years
    @DavidPetersonHarvey Please note that including <cstdio> doesn't change the fact that scanf is unaware of std::string. Unless you pass to it the underlying buffer, but that's probably not the intention of this answer's poster.