C語言 scanf輸入多個數字只能以逗號分隔的操作
阿新 • • 發佈:2020-12-10
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,c); printf("max=%d",max); return 0; } int num_max(int x,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,' '); //將字串中的','用空格代替 pos = strTemp.find(','); } sStream << strTemp; //將字串匯入的流中 while (sStream) { sStream >> array[i++]; } for (int i = 0; i < 4; i++) { cout << array[i] << " "; } cout << endl; return 0; }
以上思路僅供參考,如果有更好的方案,歡迎提出和探討。希望能給大家一個參考,也希望大家多多支援我們。