Strings taken from user in C are being scrambled - c

I have written the following C code to get in a list of strings from the user. But the stored strings are giving out weird values.
#include <stdio.h>
#include <stdlib.h>
#define MAX_STRING_LENGTH 50
void readInStrings(char* arr[],int n)
{
int i=0;
char line[MAX_STRING_LENGTH];
for(i=0;i<n;i++){
arr[i]=malloc(MAX_STRING_LENGTH);
printf("Enter another string : ");
scanf("%s",&arr[i]);
//fgets(&arr[i],MAX_STRING_LENGTH,stdin);
}
printf("Strings read in correctly.... \n");
printf("Displaying out all the strings: \n");
for(i=0;i<n;i++){
printf("%s\n",&arr[i]);
}
}
void testStringInputs()
{
printf("Enter the number of entries : ");
int n;
scanf("%d",&n);
char* strings[n];
readInStrings(strings,n);
}
Input Sample:
Enter the number of entries : 3
Enter another string : Alladin
Enter another string : Barack Obama
Enter another string : Strings read in correctly....
Displaying out all the strings:
AllaBaraObama
BaraObama
Obama
Problems:
1) Why is one string not taken in as input at all?
2) Why are the displayed strings scrambled like that?
The problem is the same if I use gets() or fgets() in place of scanf().

arr[i] is already a pointer, you don't need the &

Removing the & (as the first answerer noted) in scanf("%s",&arr[i]); and in printf("%s\n",&arr[i]); did the trick for me. Also, note if you compiled with warnings at their highest, your compiler would have told you right away that the & was misplaced.

Its better to use an array of arrays(two dimensional) instead of array of pointers.
I had a tough time correcting your code. So I changed the code to this
#include <stdio.h>
#include <stdlib.h>
#define MAX_STRING_LENGTH 50
void readInStrings(char (*arr)[MAX_STRING_LENGTH],int n)
{
int i;
for(i = 0 ; i< n+1; ++i)
fgets(*(arr+i),MAX_STRING_LENGTH,stdin);
printf("Strings read in correctly.... \n");
printf("Displaying out all the strings: \n");
for(i=0;i< n+1;i++){
printf("%s",arr[i]);
}
}
int main()
{
printf("Enter the number of entries : ");
int n;
scanf("%d",&n);
char strings[n][MAX_STRING_LENGTH];
readInStrings(strings,n);
return 0;
}

Related

How do you use scanf in a for loop so it does not stop looping on the first try?

for(int i=0;i<num; i++)
{
char word[32];
scanf(" %[^\n]s",word);
makeDictionary(word, readDictionary);
}
I have a program where I want to ask user for certain strings n times (with spacing allowed). However, when they input for example n = 2, it only loops once and exists. I know there is something wrong with my scanf.
I do Java and I'm a beginner at C. The way strings are done is very different.
This code can help you:
#include <stdio.h>
#include <string.h>
int main()
{
int N;
do
{
printf("Give me number of words :");
scanf("%d",&N);
}while(N<1);
for(int i=0;i<N;i++)
{char str[20];
printf("\nGive me the %d word :",i+1);
scanf("%s[^\n]",str);
printf("%s",str);
}
}

C Array Looping Error

I'm supposed to write a simple C program to read in an integer and loop n times to work on the string, but the first loop automatically passes an empty string if I use the scanf integer, but if I use a constant number the loop works right. Somebody please explain to me what's going on.
#include <stdio.h>
#define MAX 80
int main(){
char sentence[MAX];
int n, i;
scanf("%d", &n);
for(i=0; i<3; i++){//it loops with empty string automatically if I replace 3 with n
gets(sentence);
printf("%s\n", sentence);
}
}
Try this code
#include<stdio.h>
#include<conio.h>
#define MAX 80
void main()
{
char sentence[MAX];
int n,i;
clrscr();
scanf("%d",&n);
for(i=0;i<n;i++)
scanf(" %99[^\n]",sentence);
printf("\n%s\n",sentence);
getch();
}

Sort words in a string based on their vowel number

I must write a program in C that allows an user to say how many words they want to enter in a string and then I must sort those words based on their vowel number(the word with more vowels is first and the one with the least vowels is last - if two words have the same number of vowels then leave them in the order as they have appeared). For example:
string - "Aaaa Bbbbbbb B CD home Aaa BB A poke"
Sorted string - "Aaaa Aaa home poke A Bbbbbbb B CD BB"
I know how to write the first part, but for the sort part I have no idea. Can someone help me with that please?
EDIT: Currently I have this code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#pragma warning (disable: 4996)
int main(){
char string1[20], string2[100] = { '\0' };
int N, i;
do{
printf("Enter the number of words you want to enter in the string: ");
scanf("%d", &N);
if (N < 2){
printf("You must enter at least two words.\n");
printf("Enter the number of words you want to enter in the string: ");
scanf("%d", &N);
}
} while (N < 2);
for (i = 0; i < N; i++){
printf("Enter a word: ");
scanf(" %[^\n]", string1);
if (strlen(string2) == 0)
strcpy(string2, string1);
else {
strcat(string2, " ");
strcat(string2, string1);
}
}
printf("%s\n", string2);
return 0;
}
You will want to create an array of structs that hold a pointer to the word and then the number of vowels in each word. Something like:
struct vowelcnt {
char *word;
int numvowels;
}
Then sort the array of structs (descending order based on numvowels. Then simply loop through the sorted structs outputting the word which would give you the words sorted in order of the number of vowels contained. Hope that helps.

How to get multiple inputs in one line in C?

I know that I can use
scanf("%d %d %d",&a,&b,&c):
But what if the user first determines how many input there'd be in the line?
You are reading the number of inputs and then repeatedly (in a loop) read each input, eg:
#include <stdio.h>
#include <stdlib.h>
int main(int ac, char **av)
{
int numInputs;
int *input;
printf("Total number of inputs: ");
scanf("%d", &numInputs);
input = malloc(numInputs * sizeof(int));
for (int i=0; i < numInputs; i++)
{
printf("Input #%d: ", i+1);
scanf("%d", &input[i]);
}
// Do Stuff, for example print them:
for (int i=0; i < numInputs; i++)
{
printf("Input #%d = %d\n", i+1, input[i]);
}
free(input);
}
Read in the whole line, then use a loop to parse out what you need.
To get you started:
1) Here is the manual page for getline(3):
http://man7.org/linux/man-pages/man3/getline.3.html
2) Some alternatves to getline:
How to read a line from the console in C?
3) Consider compressing spaces:
How do I replace multiple spaces with a single space?
4) Use a loop for parsing. You might consider tokenizing:
Tokenizing strings in C
5) Be careful and remember that your user could enter anything.
#include <conio.h>
#include <stdio.h>
main()
{
int a[100],i,n_input,inputs;
printf("Enter the number of inputs");
scanf("%d",&n_input);
for(i=0;i<n_input;i++)
{
printf("Input #%d: ",i+1);
scanf("%d",&a[i]);
}
for(i=0;i<n_input;i++)
{
printf("\nInput #%d: %d ",i+1,a[i]);
}
}
/*
_______________This program is in C Programming Language_______________
We have to directly enter all the elements in one line giving spaces between them. Compiler will automatically ends the for loop I have used and assign the value to their respective variables or array indexes. Below program and output will give you better understanding.
*/
#include <stdio.h>
int main()
{
//taking no of inputs from user
int len;
printf("Enter the number of inputs you want to enter : ");
scanf("%d", &len);
int i;
//defined an array for storing multiple outputs
int arr[100];
//included a printf statement for better understanding of end user
printf("Enter the inputs here by giving space after each input : ");
/*here is the important lines of codess for taking multiple inputs on one line*/
for (i=0;i<len;i++)
{
scanf("%d", &arr[i]);
}
printf("Your entered elements is : ");
for (i=0;i<len;i++)
{
printf("%d ", arr[i]);
}
}
/*
OUTPUT :
Enter the number of inputs you want to enter : 5
5 5 5 8 7
Your entered elements is : 5 5 5 8 7
*/

while loop asks user input one time only

#include <stdio.h>
#include <stdlib.h>
struct the_struct
{
char FirstName[20];
char LastName[32];
int Score[20];
};
int main ()
{
int i,n;
struct the_struct *ptr[100];
printf("how many students?\n");
scanf("%d",&n);
while (i<=n);
{
i==0;
ptr[i] = malloc(sizeof(struct the_struct));
printf("Enter First Name \n");
scanf("%s",ptr[i]->FirstName);
printf("Enter Last Name \n");
scanf("%s",ptr[i]->LastName);
printf("Enter Score? \n");
scanf("%s",ptr[i]->Score);
printf("%s %s %s\n",ptr[i]->FirstName,ptr[i]->LastName,ptr[i]->Score);
i++;
}
}
hey guys, so when i enter the first input, it goes only once without going on for the number the user inputs, i tried the for loop but same result.
still learning C so my apology if i misunderstood something.
Thanks in advance.
Your while loop is problematic. You could rewrite it as:
for (i = 0; i < n; ++i)
{
ptr[i] = malloc(sizeof(struct the_struct));
printf("Enter First Name \n");
scanf("%s",ptr[i]->FirstName);
printf("Enter Last Name \n");
scanf("%s",ptr[i]->LastName);
printf("Enter Score? \n");
scanf("%s",ptr[i]->Score);
printf("%s %s %s\n",ptr[i]->FirstName,ptr[i]->LastName,ptr[i]->Score);
}
And since you use %s to read and print Score, you should declare it as char Score[20]; instead of int.
The problem is that i is uninitialized. Therefore, the loop while (i <= n) has undefined behavior, and can end at any time.
Add int i = 0 initializer to fix this problem.
Notes:
i == 0 expression at the beginning of the loop has no effect
Since i starts at zero, your while loop should be while (i < n), not <=.
You should check the results of scanf to see if the user entered something meaningful
You should specify the size of the array into which you read a string, e.g. scanf("%31s",ptr[i]->LastName); This prevents buffer overruns.

Resources