How to input comma separated values having integers in c++?
Answers
If your list is something like this
1,2,501,69,48,153629,6666
you can do this algorithm
Read the entire line in a buffer
Separate in tokens by “,”
For each token, call atoi(token)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int array[1024];
int length=0;
char buffer[1024];
char *aux;
fgets(buffer,1023,stdin);
aux=strtok(buffer, ",");
while(aux)
{
array[length]=atoi(aux);
length++;
aux=strtok(NULL, ",");
}
for(int i=0;i<length;i++)
{
printf("%d ",array[i]);
}
}
This will read all your comma separated numbers and store them in an array of int and then print them.
I recommend learning about strtok() and atoi().
Btw, the program above works well in most cases, when it won’t work?
Answer:
How to input a comma separated string?
Get the string to be taken as input in stringstream.
Take each character of the string one by one from the stream.
Check if this character is a comma (', ').
If yes, then ignore that character.
Else, Insert this character in the vector which stores the words.
hope it helps you
..........