如何在 C++ 中使用 scanf() 读取字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5910483/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I read a string with scanf() in C++?
提问by Elmi Ahmadov
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() ?
我可以用 with 读取一个字符串,std::cin
但我不知道如何用一个 withscanf() 来读取。如何更改下面的代码以使用 scanf() ?
string s[20][5];
for (int i=1;i<=10;i++)
{
for (int j=1;j<=3;j++)
{
cin>>s[i][j];
}
}
回答by Greg Hewgill
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
.
使用 Cscanf()
函数需要使用 C 字符串。此示例使用临时 C 字符串tmp
,然后将数据复制到目标中std::string
。
char tmp[101];
scanf("%100s", tmp);
s[i][j] = tmp;
回答by unwind
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 .
你不能,至少不能直接。该scanf()
函数是一个 C 函数,它不知道std::string
(或类),除非您包含 .
回答by Shadow2531
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.
不确定为什么需要使用 scanf 并且 Greg 已经介绍了如何使用。但是,您可以使用 vector 而不是常规字符串数组。
Here's an example of using a vector that also uses scanf (with C++0x range-based for loops):
这是使用也使用 scanf 的向量的示例(使用 C++0x 基于范围的 for 循环):
#include <string>
#include <vector>
#include <cstdio>
using namespace std;
int main() {
vector<vector<string>> v(20, vector<string>(5, string(101, '##代码##')));
for (auto& row: v) {
for (auto& col: row) {
scanf("%100s", &col[0]);
col.resize(col.find('##代码##'));
}
}
}
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.
此外,getline(cin, some_string) 通常比 cin >> 或 scanf() 好很多,这取决于您想要做什么。