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流中,然后输⼊到指定的⽂件和数组中去c语言scanf能输入中文吗
具体代码如下:
// 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 = place(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;
}
以上思路仅供参考,如果有更好的⽅案,欢迎提出和探讨。希望能给⼤家⼀个参考,也希望⼤家多多⽀持。