将字符数组转换为 int

Converting char array to int

本文关键字:int 转换 数组 字符      更新时间:2023-10-16
#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]!='' && str[i]==' ')i++;
            if(str[i]=='')return;
            arr[size] = 0;
            while(str[i]!='' && 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();
    }

在这里,我正在尝试编写一个将数字和空格字符串转换为数字数组的程序,但是它没有输出一个问题。什么可能导致此问题。我是 c++ 的乞丐,所以欢迎批评者。

return离开当前函数。摆脱无限循环的唯一方法是离开整个函数,这意味着您总是跳过输出。请改用break或为for(;;)循环提供适当的条件。

尽管 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;
    }

问题在这里只是在"k"上更改了"i"。