good month everyone
i want to input one long string and than divide it to tow separate strings
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
|
#include "stdafx.h"
#include <stdio.h>
#include <string.h>
void main()
{
char first[30], second[15] , third[15];
int n =0;
printf("put name and surname:\n");
scanf_s("%s", first[0]);
while (first[n] != ' ') {
second[n] = first[n];
n++;
}
first[n]++;
int y = 0;
while (first[n]) {
third[y] = first[n];
n++;
y++;
}
printf("%s\n", second[0]);
printf("%s\n", third[0]);
}
|
In your particular case you could simply do this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
int index = 0;
int index2 = 0;
while(first[index] != ' ')
{
second[index2] = first[index];
index++;
index2++;
}
index2 = 0;
while(first[index] != '\0')
{
third[index2] = first[index];
index++;
index2++;
}
|
If you prefer a shorter version and more flexible one this is for you:
1 2 3 4 5 6 7
|
char first[] = "test boy";
char second[20], third[20];
char *ptr = strtok(first, " ");
strcpy(second, ptr);
ptr = strtok(NULL, " ");
strcpy(third, ptr);
|
Last version uses functions strtok and strcpy from <cstring> library
strtok makes tokens of a string, the token ends where the const character from second argument is met
strcpy copies in the first argument the string from the second argument
passing NULL in the first argument in strtok takes the new token of the last string used
warning you may have to make a copy of the first string because the string will be modified
thx, why doesnt my code compile ?
thx, why doesnt my code compile ? |
Your compiler should tell you.
Works well, thank you.
what is the message "cant open or find the PDB file" ??
Topic archived. No new replies allowed.