C语言 scanf输入多个数字只能以逗号分隔的操作

Dorothy ·
更新时间:2024-09-20
· 957 次阅读

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

#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流中,然后输入到指定的文件和数组中去

具体代码如下:

// 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; }

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

您可能感兴趣的文章:解决scanf_s输入%d%c%d格式错误的问题解决C语言中使用scanf连续输入两个字符类型的问题c/c++ 利用sscanf进行数据拆分操作C++ 输入scanf()和输出printf()的操作C语言清除scanf()缓存的案例讲解



逗号分隔 scanf C语言

需要 登录 后方可回复, 如果你还没有账号请 注册新账号