In main, I pass a string to a different function that is supposed to separate the string, then work with each substring. In this case, I need to take a 30 character string and separate it into substrings of length 7, 5, 5, 7, and 6 to be manipulated later. This is what I started trying:
void breakString(const char *lineStr) {
char a[7] = " "; //I tried with them all initialized empty and without doing so.
char b[5]; //Didn't seem to make a difference.
char c[5];
char d[7];
char e[6];
//sscanf(lineStr, "%7s", &a); //tried sscanf at first, but didn't know how to
strncpy(a, lineStr, 7); //scan the middle so i switched to strncpy
strncpy(b, lineStr + 7, 5);
//continue this pattern for c,d,e
(rest of function here, where each substring is manipulated accordingly.)
I tested the first bit by printing substrings a
and b
(and also by strcmp()
them to the correct output), but it doesn't fully work. I keep getting extra gibberish. For example, if the full string passed is "abcdefghijklmnopqrstuvwxyz1234"
, then a
should be "abcdefg"
, b
should be "hijkl"
, and so on. However, when I print a
, it comes out as "abcdefg^#@%^&"
with some random assortment of characters following each substring.
What am I doing wrong? Or are there better ways to implement this differently?