C之scanf输入多个数字只能以逗号分隔,而不能用空格 TAB空白符分隔
?| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
#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流中,然后输入到指定的文件和数组中去
具体代码如下:
?| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
// 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;
}
|
以上思路仅供参考,如果有更好的方案,欢迎提出和探讨。希望能给大家一个参考,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/weixin_43636211/article/details/105829061








发表评论
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。