我是靠谱客的博主 纯情河马,这篇文章主要介绍C语言 scanf输入多个数字只能以逗号分隔的操作,现在分享给大家,希望可以做个参考。

C之scanf输入多个数字只能以逗号分隔,而不能用空格 TAB空白符分隔

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <stdio.h> int main() { int num_max(int x,int y,int z); int a,b,c,max; scanf("%d,%d,%d",&a,&b,&c); max=num_max(a,b,c); printf("max=%d",max); return 0; } int num_max(int x,int y,int z) { int max=z; if(max<x)max=x; if(max<y)max=y; return(max); }

原因是scanf 对于数字输入,会忽略输入数据项前面的空白字符。因此只能以逗号分隔。

补充知识:c++中读入逗号分隔的一组数据

如题,在面试和实际应用中,经常会碰到一个场景:读入以指定符号间隔的一组数据,放入数组当中。

看了不少博客,总结了一个个人目前觉得比较简便的方法(其实和java比也一点不简便。。。。)

基本思路就是:将输入的数据读到string中,然后将string中的间隔符号用空格代替后,输入到stringstream流中,然后输入到指定的文件和数组中去

具体代码如下:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// cin,.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include "iostream" #include <string> #include <sstream> using namespace std; int _tmain(int argc, _TCHAR* argv[]) { string strTemp; int array[4]; int i = 0; stringstream sStream; cin >> strTemp; int pos = strTemp.find(','); while (pos != string::npos) { strTemp = strTemp.replace(pos, 1, 1, ' '); //将字符串中的','用空格代替 pos = strTemp.find(','); } sStream << strTemp; //将字符串导入的流中 while (sStream) { sStream >> array[i++]; } for (int i = 0; i < 4; i++) { cout << array[i] << " "; } cout << endl; return 0; }

以上思路仅供参考,如果有更好的方案,欢迎提出和探讨。希望能给大家一个参考,也希望大家多多支持靠谱客。

最后

以上就是纯情河马最近收集整理的关于C语言 scanf输入多个数字只能以逗号分隔的操作的全部内容,更多相关C语言内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(177)

评论列表共有 0 条评论

立即
投稿
返回
顶部