0
#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.

6
  • Why do you think that critics only welcome to beginners? Commented Jan 17, 2018 at 17:01
  • 1) char str[] -> std::string or std::array<char>. 2) I highly encourage you to learn how to use a debugger Commented Jan 17, 2018 at 17:02
  • I just began to learn c++ and don't konw how to use dynamical arrays, but thanks Commented Jan 17, 2018 at 17:12
  • 2
    please don't edit your question so that the given answers becomes incorrect. Commented Jan 17, 2018 at 17:21
  • Sorry, didn't know Commented Jan 17, 2018 at 17:26

2 Answers 2

1

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;
}
Sign up to request clarification or add additional context in comments.

Comments

0
    for(int k = 0;k<size;k++)
    {
        cout <<arr[k]<<endl;
    }

problem was here just changed 'i' on 'k'.

1 Comment

Good catch, but it's not the only problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.