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

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

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

天下没有不散的宴席,也许这人间真的只有朦朦胧胧才是真。

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

相关文章:

你感兴趣的文章:

标签云: