How can I read a string with scanf() in C++?
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];
开发者_JAVA百科 }
}
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;
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 .
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.
精彩评论