因为visual studio用不了gets,拜托了
用atoi阿...
取数字会不会,有string类型阿。。
#include <string>
#include <iostream>
using namespace std;
#pragma warning(disable:4996)
int main()
{
string x = "a123b456";
string s;
int j = 0;
for (int i = 0; i < x.size(); i++) {
if (x.at(i) >= '0' && x.at(i) <= '9') {
s.push_back(x.at(i));
}
else {
printf("%s\n", s.data());
j++;
s.clear();
continue;
}
}
printf("%s\n", s.data());
printf("%d", j);
return 0;
}
C++有更正宗的输入输出iostream呀。
#include <iostream>
using namespace std;
int main()
{
cout << "Please enter a line of text with digits and nun-digit characters: " << endl;
string buffer;
getline(cin, buffer);
int numbers[100];
int count = 0;
for (int i = 0; i < buffer.length(); ++i)
{
if (buffer[i] >= '0' && buffer[i] <= '9')
{
int n = 0;
for (; i < buffer.length() && buffer[i] >= '0' && buffer[i] <= '9'; ++i)
{
n = n * 10 + (buffer[i] - '0');
}
numbers[count++] = n;
}
}
cout << "The numbers embedded in the line are: " << endl;
for (int i = 0; i < count; ++i)
{
cout << numbers[i] << endl;
}
return 0;
}
// Output
Please enter a line of text with digits and nun-digit characters:
abc123cde345 678$%^9^&*10a100mmm88great1
The numbers embedded in the line are:
123
345
678
9
10
100
88
1
改成了用fgets和atoi:
#include <iostream>
#include <stdlib.h>
#include <string.h>
using namespace std;
int main()
{
cout << "Please enter a line of text with digits and nun-digit characters: " << endl;
char buffer[1024];
fgets(buffer, 1024, stdin);
int numbers[100];
int count = 0;
for (int i = 0; i < strlen(buffer); ++i)
{
if (buffer[i] >= '0' && buffer[i] <= '9')
{
int n = atoi(buffer + i);
i += to_string(n).length();
numbers[count++] = n;
}
}
cout << "The numbers embedded in the line are: " << endl;
for (int i = 0; i < count; ++i)
{
cout << numbers[i] << endl;
}
return 0;
}
// Output
Please enter a line of text with digits and nun-digit characters:
abc123cde345 678$%^9^&*10a100mmm88great1
The numbers embedded in the line are:
123
345
678
9
10
100
88
1
您好,我是有问必答小助手,您的问题已经有小伙伴解答了,您看下是否解决,可以追评进行沟通哦~
如果有您比较满意的答案 / 帮您提供解决思路的答案,可以点击【采纳】按钮,给回答的小伙伴一些鼓励哦~~
ps:问答VIP仅需29元,即可享受5次/月 有问必答服务,了解详情>>>https://vip.csdn.net/askvip?utm_source=1146287632