0

I want to input:

abc def ghi jkl

and the output should be:

abc
def
ghi
jkl

I want to store each string in an array and then use a for cycle to print each position.

I have this code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    char vector[100];
    int i = 0;
    int aux = 0;
    while (i < 5)
    {
        scanf("%s", &vector[i]);
        i++;
        aux+= 1;
    }

    for (i=0;i<aux;i++)
    {
        printf("%s\n", &vector[i]);
    }

    return 0;
 }

What am I doing wrong?

Second question:

How can I change the code to stop reading my inputs when I press ctrlD and print the output?

3 Answers 3

2

You're taking the address of a character in your "vector", in stead of filling up a few strings. These modifications:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    char vector[5][100]; /* five times 100 characters, not just 100 characters */
    int i = 0;
    int aux = 0;
    while (i < 5)
    {
        scanf("%s", vector[i]); /* notice the & is gone */
        i++;
        aux+= 1;
    }

    for (i=0;i<aux;i++)
    {
        printf("%s\n", vector[i]); /* notice the & is gone */
    }

    return 0;
 }

As for the ctrl-D bit, you can have it stop reading at the end of input, but you'd have to manage getting lots of input (so you'd potentially have to dynamically allocate the buffer into which you "parse" your string with scanf)

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. Done what you said and it worked. Changed the while loop for while (i <5 && scanf("%s", vector[i])!=EOF) and now it stops wen i press ctrl d but if I input a b c and press ctrl d it prints a after the c input and b and c on new lines. How can I change that?
@Favolas Can you post your new code? It'll be easier to answer you (apparently new) question with that.
Thanks for the help. Here it is stackoverflow.com/questions/5535916/…
0

You are using a single array of char to store multiple string. You could use an 2d array this way:

char vector[STRING_NUM][STRING_MAX_LENGTH]

Comments

0

You have an array of characters (i.e. one string).

If you want an array of strings, that's an array of arrays of characters:

char vector[NUM_STRINGS][NUM_CHARS];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.