赞
踩
我们在刷牛客网的题目时,经常遇到多组输入,执行到文件结束,下面介绍几种写法
1、C语言的输入多个整数
- while(scanf("%d", &n) != EOF){ // 为End Of File的缩写,通常在文本的最后存在此字符表示资料结束
- /*
- code
- */
- }
2、C++输入字符串string
- int main()
- {
- string str;
- getline(cin, str)
- cout<< str<<endl;
- return 0;
- }
3、C++输入字符串char数组
- int main()
- {
- char str[100];
-
- while (gets(str))
- {
- cout << str;
- }
- return 0;
- }
4、 C++输入一组数据
- template<typename T>
- vector<T> ReadVector(int count) // 任意类型的数组
- {
- vector<T> result(count);
- for (int i = 0; i < count; i++)
- {
- cin >> result[i];
- }
- return result;
- }
-
- int main()
- {
- int num = 0;
- cin >> num;
- vector<string> res = ReadVector<string>(num);
-
- for (auto &row : res)
- {
- cout << row << " ";
- }
- return 0;
- }
5、 输入回车,判断当前输入结束
- int main()
- {
- vector<int> result;
- int a;
- while (cin >> a)
- {
- result.push_back(a);
- if (getchar() == '\n')
- {
- break;
- }
- }
-
- int i = 0;
- while (result.size() > i)
- {
- cout << result[i++] << " ";
- }
- return 0;
- }
6、输入多个数据
- char a;
- int b;
- float c;
- cin >> a >> b >> c;
- cout << a << " " << b << " " << c << " " << endl;
7、输入结构体
- typedef struct tgStudent
- {
- char name[100];
- int number;
- int score;
-
- }Student;
-
- int main() {
- int num;
- cin >> num;
-
- Student* studentList = new Student;
- for (size_t i = 0; i < num; i++)
- {
- cin >> studentList[i].name >> studentList[i].number >> studentList[i].score;
- }
-
- for (int j = 0; j < num; j++)
- {
- cout << studentList[j].name << " ";
- cout << studentList[j].number << " ";
- cout << studentList[j].score << " ";
- cout << endl;
- }
- }
8、输入字符串数组
- int g_row, g_col; //行、列数
- char waitWord[101] = { '\0' }; //待查找的单词
- char maze[100][21] = { {'\0'} }; //字母矩阵
- int main()
- {
- cin >> g_row >> g_col; //输入行、列数
- cin.get(); //去掉回车符
- cin.getline(waitWord, 100); //输入待查找的单词
- for (int i = 0; i < g_row; i++)
- {
- cin.getline(maze[i], 21); //输入字母矩阵
- }
- system("pause");
- return 0;
- }
注意:在终端中手动输入时,系统并不知道什么时候到达了所谓的“文件末尾”,必须输入以下字符才能结束输入:
参考:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。