I have a string "token" and an empty array of strings "arr". I want to add token to the first index of arr. I've tried arr[0][0] = token, but this would only work for chars and I've also tried arr[0] = token but this throws the error "expression must be a modifiable lvalue". My full program is:
#include <stdio.h>
#include <string.h>
char arr[100][100] = {};
char *token = strtok(StringToBeSplit, " ");
int i = 0;
while(token != NULL) {
arr[0] = token;
printf("%s\n", token);
token = strtok(NULL, " ");
i++;
}
What should I do?
You need to avoid assigning string literal to strtok. Basically using strcpy to copy the token to array and increment array as advised by previous answer. Something like this:-
#include <stdio.h>
#include <string.h>
int main(){
char arr[100][100] = {};
char str[] = "Split this string";
char sep[] = " ";
char *token = strtok(str, sep);
int i = 0;
while(token != NULL){
strcpy(arr[i], token);
token = strtok(NULL, sep);
i++;
}
//Test If it can print the strings
for(int j = 0; j < i; j++)
printf("%s\n", arr[j]);
}
I created a function to split a string with comma.
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
char splitted_line[8][50];
void split(char *line){
printf("line 9\n");
char *part = strtok(line, ",");
printf("line 11\n");
for(int i=1; i<8; i++){
strcpy(splitted_line[i], part);
printf("%s\n", splitted_line[i]);
part = strtok(NULL, ",");
}
}
int main(){
char *line = "123,456,789";
split(line);
return 0;
}
but the result after running is :
line 9
Segmentation fault (core dumped)
it seems the problem is in char *part = strtok(line, ","); but I don't know what's that.
strtok() will modify passed original string directly.
You must not modify string literals.
char *line = "123,456,789";
should be modifyable array
char line[] = "123,456,789";
Also don't forget to check if part is not NULL before doing strcpy(splitted_line[i], part);.
I have read through countless strtok posts, even copied some directly in their entirety into a new int main, but I can't figure out how to create the functions get_first and get_second.
get_first("This is a sentence."); //returns "This"
get_rest("This is a sentence."); //returns "is"
This is what I have so far, I have had nothing but trouble with strtok, but I don't know what else to use.
#include <stdio.h>
#include <string.h>
char * get_first(char * string) {
string = strtok(string, " ");
return string;
}
char * get_second(char * string) {
string = strtok(string, " ");
string = strtok(NULL, " ");
return string;
}
int main(int argc, char * argv[]) {
char * test_string = "This is a sentence.";
char * first = get_first(test_string);
char * second = get_second(test_string);
printf("%s\n", first);
printf("%s\n", second);
}
Getting no faults compiling with gcc -g -Wall, but it always seg faults. I think I have tried every permutation of char c[] and char * c there is.
strtok changes the string. (but String literals are not allowed to change.)
So create a copy.
Do the following:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char * get_first(const char *string){
char *clone = strdup(string);//create copy, strdup is non standard. malloc and copy.
char *token = strtok(clone, " ");
if(token)
token = strdup(token);
free(clone);
return token;
}
char * get_second(const char *string) {
char *clone = strdup(string);
char *token = strtok(clone, " ");
if(token && (token = strtok(NULL, " ")))
token = strdup(token);
free(clone);
return token;
}
int main(void) {
char * test_string = "This is a sentence.";
char * first = get_first(test_string);
char * second = get_second(test_string);
printf("%s\n", first);
printf("%s\n", second);
free(first);
free(second);
}
I'm sorry in advance because I'm fairly new to programming and some things in my code will probably look like utter nonsense! I'm not entirely sure if I'm using atoi right.
I'm trying to create a program that splits a user input sentence into single words and doubles the number(float/integer) if a user inputs one.
For example, I have 3 cats would come out as:
I
have
6
cats
My program right now is able to split the sentence, but I can't get the integer to double. Can anyone help me with this?
Here is the code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void main()
{
char sentence[100];
printf("Enter a sentence to split: ");
scanf("%[^\n]s", sentence);
char *pch;
int y;
y = atoi(sentence);
printf("After splitting:\n", sentence);
pch = strtok(sentence," ");
while (pch != NULL) {
printf("%s\n", pch);
pch = strtok(NULL, " ");
}
system("PAUSE");
}
And my output so far:
Enter a sentence to split: Hi, I have 7 cats.
After splitting:
Hi,
I
have
7
cats.
Press any key to continue . . .
Here is a simpler version with a test for all digit numbers:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
char sentence[100];
char *pch;
printf("Enter a sentence to split: ");
if (!fgets(sentence, sizeof sentence, stdin))
return 1;
printf("After splitting:\n");
for (pch = strtok(sentence, " \n"); pch != NULL; pch = strtok(NULL, " \n")) {
if (pch[strspn(pch, "0123456789")] == '\0') {
printf("%d\n", atoi(pch) * 2);
} else {
printf("%s\n", pch);
}
}
system("PAUSE");
return 0;
}
If you want to parse floating point numbers too, you could use this code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
int main(void) {
char sentence[100];
char *pch, *pend;
double value;
printf("Enter a sentence to split: ");
if (!fgets(sentence, sizeof sentence, stdin))
return 1;
printf("After splitting:\n");
for (pch = strtok(sentence, " \n"); pch != NULL; pch = strtok(NULL, " \n")) {
value = strtod(pch, &pend);
if (*pend == '\0' && isfinite(value)) {
printf("%g\n", value * 2);
} else {
printf("%s\n", pch);
}
}
system("PAUSE");
return 0;
}
Note the test for isfinite() to avoid recognizing inf and nan as numbers.
NOTE: isfinite is part of C99, it is not supported by VisualStudio 12, but more recent versions do support it. For this older version, use _finite() defined in <float.h>.
Here is a working example, even if it's not really precise. Basically, we need to find out whether our current string is a number or not. In this case, I just tried to get the first element of the current string, and tried to determine if it's numeric or not.
Of course, if you want to be really sure, we need to iterate the string and check every char, if it is a number or not.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void main()
{
char sentence[100];
printf("Enter a sentence to split: ");
scanf("%[^\n]s", sentence);
char * pch;
int y;
y = atoi(sentence);
printf("After splitting:\n", sentence);
pch = strtok (sentence," ");
while (pch != NULL)
{
if(isdigit(pch[0]))
{
int number = atoi(pch);
number *=2;
printf("%d\n",number);
pch = strtok (NULL, " ");
continue;
}
printf("%s\n",pch);
pch = strtok (NULL, " ");
}
system("PAUSE");
}
For the split part I would recommend this version, it is easier to understand (considering that you've learned the for way of working). It does the same thing, but helps you organize your code.
char *p;
int i;
for(p = strtok(sentence, " "); p != NULL; p = strtok(NULL, " "))
{
int isNumber = 1;
for(i = 0; i < strlen(p); i ++)
{
if(!isDigit(p[i])
{
isNumber = 0;
break;
}
}
if(isNumber == 1)
{
int number = atoi(pch);
number *= 2;
printf("%d\n", number);
}
else
{
printf("%s\n", p);
}
}
For the number, I would recommend using the atoi function. Here you have a good reference.
To solve your problem, first of all, you need to check every single word you get. For example: You take it word by word and see if the "word" contains ONLY digits. If it contains only digits, you can use atoi to convert it to a number, multiply it by 2 and print the result.
On the other hand, if you find a char that is NOT a digit, you have letters or any other characters in your word, so it is not a word so you simply print that as it is.
Here's another (more compact) answer:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int is_numeric(char *s)
{
int i = 0;
while (s[i] != '\0') {
if (!isdigit(s[i]))
return 0;
++i;
}
return 1;
}
int main()
{
char sentence[255];
char *pch;
printf("Enter a sentence to split: ");
if (!fgets(sentence, sizeof(sentence), stdin)) {
return 1;
}
sentence[strcspn(sentence, "\n\r")] = 0; /* Strip newline */
pch = strtok(sentence, " ");
while (pch != NULL) {
if (atoi(pch)) {
printf("%d\n", 2 * atoi(pch));
} else {
printf("%s\n", pch);
}
pch = strtok(NULL, " ");
}
return 0;
/* system("PAUSE"); */
}
The key is that atoi will return 0 for a non-numeric argument.
I'm trying to split a string at spaces and tabs.
char * token = strtok(input, " \t");
works only for spaces. What am I doing wrong?
Here is an example that illustrates that strtok() will work on tabs or spaces.
The key is to pass in NULL on the all but the first call to strtok().
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
char buffer[1024];
int rv = sprintf(buffer, "a string\ttokenize.");
char *token = strtok(buffer, " \t");
int i = 0;
printf("cnt token\n");
printf("==========\n");
while (token) {
printf("%2d %s\n", i++, token);
token = strtok(NULL, " \t");
}
return 0;
}
output from above program is as follows below.
cnt token
==========
0 a
1 string
2 tokenize.