Jump to content

Newbie questions regarding inputing a sentence

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
3 replies to this topic

#1
Emir

Emir

    Newbie

  • Members
  • Pip
  • 5 posts
Hello everyone,

I've got this school assignment that I must do, but I have certain problems with it.

(I'm programming use the programing language C, btw)

[Please do not flame me, I'm new and I'm probably asking some very newbie questions :) ]

The assignment is as follows:
1) I am to make a small program that in which the user is to input some text and the program outputs the same text, but removes 'white spaces' (tabs \t, new lines \n, double spaces, etc).

2) the second assignment is basically the same this as the first one, accept the user inputs a string that represents C programing language code and removes all the comments.

The problem is I don't know how to do that. :( We've been introduced to the %s which inputs a string the user enters, but it stops on the first space and doesn't go further. I know that, but how do I enable the program to accept the whole thing, with white spaces?

For example, my program should do the following:
user input: This is a /n sample /t code .
program output: This is a sample code.

(don't worry about my program exceeding the array limit, it's not an issue here)

Alright, now here's my code:


#include <stdio.h>

#include <stdlib.h>


int main()

{

    char niz[50];

    int i=0;


    printf ("String plz \n");

    scanf ("%s", niz);

    getchar();


    for (i=0; i<50; i++)

    {

        if ( niz[i]=='\0')

        break;


        printf ("%c", niz[i]);

    }


    printf ("\n TEST %c", niz[5]);

    return 0;

}


Thanks for everyone in advance!

#2
WingedPanther

WingedPanther

    A spammer's worst nightmare

  • Moderators
  • 16,831 posts
Try using the getline() function.
Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog

#3
Freedom Doc

Freedom Doc

    Newbie

  • Members
  • Pip
  • 8 posts

WingedPanther said:

Try using the getline() function.

The OP said he was using C. There is no getline() in C.
(If the OP is cool with using C++ he should say so).

To the OP: if you just need to read a sentence into a string, try fgets:

fgets(buff, 80, stdin);

would read 80 chars from stdin, or up to end of line or end of file, whatever comes first.
What it reads goes into buff, which should be declared
char buff[81];
If you want to read such a string from a file, say FILE *f then just say
fgets(buff, 80, f);
assuming f has been opened.

#4
dargueta

dargueta

    Writes binary right handed and hex left handed

  • Moderators
  • 4,720 posts
There's a simpler way to do it. In both cases, just use scanf (fscanf for the file), but set the delimiter to the newline character. In other words, your format string should be "%[^\n]s".