Printing a line

Hello, I want your help in C. I have a file which contains lines with spaces. When I use printf("%s",str) it prints my data in new lines but I want to display them in a single line. Is there any way to do it? Thanks!

i.e. Iwant:
My Book 1

and not:

My
Book
1
Check yo make sure your strings do not contain newline characters - printf does not add a new line unless you specify that with \n
1
2
printf("\nTitle: %s ",book->title);
  printf("\nSummary: %s ",book->summary);


This is a part of my code. I want the first line to print me: My Book 1 but it prints:
My
Book
1

I do not use \n at the end...I am confused!
The code you show should print at least:
Title:
Summary:

You should show more of your code.
Sorry...
I found how to print the whole string! I used fgets and printf worked fine!
Can you help me now how to insert a string with spaces? Like: My Book 1.
I used gets but it does not work...Is there any other command to read string with spaces?
Thanks!!
http://www.cplusplus.com/reference/string/string/getline/

Insert string to where?
a = b + " " + c;


Edit:
If you already do have words in b and c, you could concatenate them with
1
2
char a[N];
snprintf( a, N, "%s %s", b, c );

If book->title is equivalent to a, then use book->title instead.
Last edited on
@keskiverto he needs help in C, not C++
To a pointer: book->title. Hope this helps you! Thanks!
Something like this:

1
2
3
4
5
struct Book
{
    char title[100] ;
    // ...
};


And then:
1
2
3
4
5
6
7
8
9
Book b ;
Book* book = &b ;

// read a full line upto a  maximum of 100 characters in length
// the line may contain spaces
char* p = fgets( book->title, 100, stdin ) ;

// remove the new line at the end
if(p) book->title[ strlen(p) - 1 ] = 0 ;

fgets reads a string from a file. I want to take a string with spaces from user. gets does not work and I don't know why. I want to take as input: My Book (with the space) and store it in book->title.
Last edited on
Why when I try to use this:

1
2
3
4
char title[256];

printf("Give the title: ");
fgets(title, 256, stdin);


It does not let me write anything and just passes this input?
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <stdio.h>
#include <string.h>

int main(void)
{
  char title[256];

  printf("Give the title: ");
  char * p = fgets(title, 256, stdin);
  if (p)
    {
      title[ strlen(p) - 1 ] = 0;

      printf("\n%lu '%s'\n", strlen(p), title);
    }
  return 0;
}

Produces for me:
1
2
3
Give the title: foo bar

7 'foo bar'

In what environment do you run your program?
Last edited on
> It does not let me write anything and just passes this input?

Most probably because you have stuff left over from earlier inputs in the stdin input buffer.
And that left over stuff includes a new line.
Topic archived. No new replies allowed.