user3789296
user3789296

Reputation: 23

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

I have a char array (lets' say "13 314 43 12") and i want to put the first number (13) into a separate integer . how do i do that ? is there any way like splitting the first number into 10 + 3 and then adding them to the int ?

Upvotes: 1

Views: 3951

Answers (4)

Sandun Madola
Sandun Madola

Reputation: 890

According to your question I think following code will give some idea.

#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     
        }               
    }        
}

If you want to print first number you can use

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

If you want to split and print all integers Ex: 13 as 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     
    }               
} 

Upvotes: 0

CompuChip
CompuChip

Reputation: 9232

I am not sure what you mean by getting 1 and 3, but if you want to split the space-separated string into integers I suggest using a stream.

std::istringstream iss(s);   

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

[edit] Alternatively, you could parse the string yourself, something like this:

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;

Upvotes: 6

Steven Edison
Steven Edison

Reputation: 527

If you just want the first number, just use a function like atoi() or strtol(). They extract a number until it runs into the null terminated character or a non-numeric number.

Upvotes: 1

ForceBru
ForceBru

Reputation: 44828

#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;
}

Upvotes: 1

Related Questions