#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
int findInteger(char *p,int *a)
{
int j,n = 0,i,k;
char temp[100];
for (i=0;p[i]!='\0';i++)
{
j = 0;
while (p[i] <= '0' && p[i] <= '9')
{
temp[j] = p[i];
j++;
i++;
}
if (j!=0)
{
*a = atoi(temp);
a++;
n++;
for (k=0; k<j; k++)
temp[k]=0;
i--;
}
}
return n;
}
int main()

{
int i, m, a[100];
char line[100];
cout << "請輸入一個字串:"<<endl;
gets_s(line);
m = findInteger(line, a);
cout << "字串共有:" << m << "整數" << endl;
for (i = 0; i < m; i++)
cout << setw(8) << a[i];
cout << endl;
system("pause");
return 0;
}
我輸入了字串和整數以后,總顯示字串中共有:0個整數。
但實際字串中是有整數的。
uj5u.com熱心網友回復:
修改如下,供參考:#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
int findInteger(char *p,int *a)
{
int j,n=0,i,k;
char temp[100];
for (i=0;p[i]!='\0';i++)
{
j = 0;
while (p[i] >= '0' && p[i] <= '9')//樓主這里條件輸錯了
{
temp[j] = p[i];
j++;
i++;
}
if (j!=0)
{
temp[j] = '\0'; //這里增加一個結束符
*a = atoi(temp);
a++;
n++;
for (k=0; k<j; k++)
temp[k]=0;
i--;
}
}
return n;
}
int main(int argc, char* argv[])
{
int i, m, a[100];
char line[100];
cout << "請輸入一個字串:"<<endl;
gets(line);
m = findInteger(line, a);
cout << "字串共有:" << m << "組整數" << endl;
for (i = 0; i < m ; i++)
cout << setw(8)<< a[i];
cout << endl;
system("pause");
return 0;
}
uj5u.com熱心網友回復:
for (k=0; k<j; k++)
temp[k]=0;
這兩行代碼冗余,因為上面已經有 temp[j] = '\0';,所以不需要再初始化為0了。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/228048.html
標籤:新手樂園
下一篇:二維陣列
