0

I am reading from a textfile and there is a pattern. I am currently reading the file with help of tokens. There are many lines and the pattern breaks if there are any spaces or row breaks after the pattern is finished. This is what I have tried so far:

char newLine[10];
strcpy(newLine, "\n");
int stringValue;
....
*readfromfile*
{
    ...
    stringValue = strcmp(token, newLine);
    if(stringValue == 0)
    {
        ...

So if there is a new line or blank space after the line I want the if statement to go through. Does anyone know how to solve this? Is it that token doesn't aquire the character, " " and "\n". If so, what can I do to solve it?

Fjodor
  • 529
  • 1
  • 7
  • 19
  • 2
    Please include a complete (preferably compilable) but minimal example of the problem: Answering this as it is would mean lots of guesswork about what your code does or what you want it to do. – Jussi Kukkonen Sep 29 '14 at 07:54

2 Answers2

0

Just trim(newline) before calling strcmp(). trim() will remove any blanks at the beginning or the end of the string.

You can found an example in C in this question.

There's another way: if there's blanks at the end of newLine that you don't want to compare by using strcmp(), use strncmp() instead (with the length of token).

Community
  • 1
  • 1
nouney
  • 4,363
  • 19
  • 31
  • Do I need to implement the definition for trim? – Fjodor Sep 30 '14 at 10:48
  • @Fjodor Yes you do, but it's quite trivial to implement you know. You can found an example [here](http://stackoverflow.com/questions/122616/how-do-i-trim-leading-trailing-whitespace-in-a-standard-way). – nouney Sep 30 '14 at 10:51
0

As per your comment you are reading buffer first and then want to remove characters then do as below example, (with assumption your buffer size is of 1024)

int RemoveTokens(char *string)
{
   char  buf[1024] = {0};
   int   i         = 0;
   int   j         = 0;

   strncpy(buf, string, 1024);
   memset(string, 0x00, 1024);
   for (i=0; i<1024; i++)
   {
      if (' ' != buf[i] && '\n' != buf[i])
      {
         string[j] = buf[i];
         j++;
      }
   }
}

Hope it will helps you to do it easily. :D

ravibhuva9955
  • 199
  • 1
  • 11
  • token represents the whole string between a divider, example: "!". And I want to remove the blank space from the beginning/ending of the whole string. – Fjodor Sep 29 '14 at 10:35
  • One question: You are reading string first and then want to strip down your string or you want to read file continuously and need to store it without blank spaces and new line character? – ravibhuva9955 Sep 29 '14 at 11:18
  • I am reading the string first and then I want to remove blank and new line from the beginning and ending. – Fjodor Sep 30 '14 at 10:39
  • Then if you don't have memory related issues then simply take other local buffer in which you just store whole string and then copy it again to original buffer without blank space and new line character. – ravibhuva9955 Oct 01 '14 at 05:39