Reputation: 125
#include <QtCore/QCoreApplication>
#include<iostream>
#include<cmath>
#include<cstdlib>
#include<cstdio>
#include<cctype>
using namespace std;
void test()
{
int arr[10];
int size = 0;
int i = 0;
char str[] = "12 45 1666";
for(;;)
{
while(str[i]!='\0' && str[i]==' ')i++;
if(str[i]=='\0')return;
arr[size] = 0;
while(str[i]!='\0' && str[i]!=' ')
{
if(!isdigit(str[i]))
{
cout <<str[i]<<" - Not a number!"<<endl;
return;
}
arr[size]=arr[size]*10+(str[i]-48);
i++;
}
size++;
}
for(int k = 0;i<size;k++)
{
cout <<arr[k]<<endl;
}
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
test();
return a.exec();
}
Here I'm trying to write a programm which convert string of figures and spaces to numeral array, but there is a problem it doesn't output. What could cause this problem. I'm a begginer to c++ so critics is welcome.
Upvotes: 0
Views: 885
Reputation: 29032
return
leaves the current function. The only way out of your infinite loop is by leaving the entire function, meaning you always skip the output. Use break
instead or supply an appropriate condition to your for(;;)
loop.
Though c++ already provides std::stringstream
for doing just that.
#include <iostream>
#include <sstream>
#include <string>
int main()
{
std::stringstream stream("12 45 1666");
int result;
// Reads from the stream until it's exhausted or fails
while (stream >> result)
{
std::cout << result << '\n';
}
return 0;
}
Upvotes: 1
Reputation: 125
for(int k = 0;k<size;k++)
{
cout <<arr[k]<<endl;
}
problem was here just changed 'i' on 'k'.
Upvotes: 0