C語言 scanf輸入多個數(shù)字只能以逗號分隔的操作
C之scanf輸入多個數(shù)字只能以逗號分隔,而不能用空格 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 對于數(shù)字輸入,會忽略輸入數(shù)據(jù)項前面的空白字符。因此只能以逗號分隔。
補充知識:c++中讀入逗號分隔的一組數(shù)據(jù)
如題,在面試和實際應用中,經(jīng)常會碰到一個場景:讀入以指定符號間隔的一組數(shù)據(jù),放入數(shù)組當中。
看了不少博客,總結(jié)了一個個人目前覺得比較簡便的方法(其實和java比也一點不簡便。。。。)
基本思路就是:將輸入的數(shù)據(jù)讀到string中,然后將string中的間隔符號用空格代替后,輸入到stringstream流中,然后輸入到指定的文件和數(shù)組中去
具體代碼如下:
// 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; }
以上思路僅供參考,如果有更好的方案,歡迎提出和探討。希望能給大家一個參考,也希望大家多多支持腳本之家。