繁体   English   中英

从char数组读取空格分隔的数字以分隔int

[英]Read space separated numbers from char array to separate int(s)

我有一个char数组(让我们说“ 13 314 43 12”),我想将第一个数字(13)放入一个单独的integer中。 我怎么做 ? 有什么方法可以将第一个数字拆分为10 + 3,然后将它们加到int上吗?

我不确定得到1和3是什么意思,但是如果要将空格分隔的字符串拆分为整数,建议使用流。

std::istringstream iss(s);   

int n;
while(iss >> n)
{
    std::cout << "Integer: " << n << std::endl;
} 

[edit]或者,您可以自己解析字符串,如下所示:

char* input = "13 314 43 12";

char* c = input;
int n = 0;
for( char* c = input; *c != 0; ++c )
{
   if( *c == ' ')
   {
       std::cout << "Integer: " << n << std::endl;
       n = 0;
       continue;
   }

   n *= 10;
   n += c[0] - '0';
}

std::cout << "Integer: " << n << std::endl;
#include <cstring>
#include <iostream>
#include <stdlib.h>

int main ()
{
  char str[] = "13 45 46 96";

  char * pch = strtok (str," ");

  while (pch != NULL)              
  {
      std::cout << atoi(pch)  << "\n"; // or int smth=atoi(pch)
      pch = strtok (NULL, " ");
  }
  return 0;
}

如果只想要第一个数字,请使用atoi()或strtol()之类的函数。 他们提取一个数字,直到它遇到以空终止的字符或非数字数字。

根据您的问题,我认为下面的代码会给您一些帮助。

#include <string>
#include <iostream>
using namespace std;

int main(){
    char s[] =  "13 314 43 12";
    //print first interger
    int v = atoi(s);
    cout << v << std::endl; 
    //print all integer
    for (char c : s){
        if (c == ' ' || c == '\0'){

        }else{        
            int i = c - '0'; 
            cout << i << std::endl; // here 13 print as 1 and 3     
        }               
    }        
}

如果要打印第一个号码,可以使用

int v = atoi(s);
cout << v << std::endl;

如果要拆分并打印所有整数,例如:13为1,3

for (char c : s){
    if (c == ' ' || c == '\0'){

    }else{        
        int i = c - '0'; 
        cout << i << std::endl; // here 13 print as 1 and 3     
    }               
} 

暂无
暂无

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

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