简体   繁体   English

将char数组转换为int

[英]Converting char array to int

#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. 我是C ++的入门者,因此欢迎批评家。

return leaves the current function. return离开当前函数。 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. 请改用break或为您的for(;;)循环提供适当的条件。

Though c++ already provides std::stringstream for doing just that. 尽管c ++已经提供了std::stringstream来做到这一点。

#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;
}
    for(int k = 0;k<size;k++)
    {
        cout <<arr[k]<<endl;
    }

problem was here just changed 'i' on 'k'. 问题在这里只是在“ k”上更改了“ i”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM