scanf 读入 string 注意点

2023-03-07,,

在做题的时候需要读入字符串,但是又不想使用char 数组,于是采用string存储,当时遇到了scanf读取string失败,查阅资料后总结下。

scanf是c的标准输入输出流,想要读入string,需要提前对string分配足够大的空间,否则会截断数据,其次scanf的参数需要string[0]。

test 1: read a signle string using scanf
#include <bits/stdc++.h>
using namespace std;
int main()
{
string word;
word.resize(100); // 提前分配好空间,更建议使用cin
scanf("%s", &word[[0]);
cout << word << endl;
return 0;
}
test 2: read a vector string using scanf
#include <bits/stdc++.h>
using namespace std;
int main()
{
vector<string> words;
string word;
word.resize(100);
for(int i = 0; i < 3; i++)
{
scanf("%s", &word[0]);
words.push_back(word);
}
return 0;
}
补充提高cin速度,一行代码搞定:

std::ios::sync_with_stdio(false);

scanf 读入 string 注意点的相关教程结束。

《scanf 读入 string 注意点.doc》

下载本文的Word格式文档,以方便收藏与打印。