scanf a string with size limit without ignoring spaces - c

i having problem scaning strings into a matrix that each string is maximum 256 long.
it tried this but it didnt work, someone have a solution?
#include<stdio.h>
#include<string.h>
void main()
{
char* song[5][256];
for (int i = 0; i < 5; i++)
scanf("%255[^\n]s", song[i]);
}

welcome to stackoverflow,
first of all i am not sure why you are using char *song[5][256],but you can achieve the required out by using a 2-dimentional array ie..char song[5][256].and also i am sure that using scanf function for a matrix like array will always cause a trouble.
#include<stdio.h>
int main()
{
char s[5][256];
for(int i=0;i<5;i++)
{
for(int j=0;j<256;j++)
{ char c=getchar();
if(c=='\n'||c== EOF)
{
s[i][j]='\0';
printf("\n");
break;
}
if(j<255)
s[i][j]=c;
if(j==255)
s[i][j]='\0';
}
printf("the given string %d is:%s \n",i+1,s[i]);
}
return 0;
}
And also i have used two for loops, for assigning the elements of that array.Now the code works fine.I used s insted of your variale name song.
Hope that I answered your question.

Related

Why is this dynamic char array not getting correct inputs in C?

I'm experimenting with this very basic code and running into some memory problems.
I noticed that the char array is not reading the inputs correctly, probably eating up a new line input. The program worked fine for an int array but I still get a warning about de-referencing NULL pointer.
Here's the char array,
#include <stdio.h>
#include<stdlib.h>
int main()
{
int N, i;
char* set;
scanf_s("%d", &N);
set = (char*)calloc(N, sizeof(char));
for (i = 0; i < N; i++)
{
scanf_s("%c", (set+i), 1);
}
for (i = 0; i < N; i++)
{
printf("%c", *(set + i));
}
return 0;
}
Here's the int array,
#include <stdio.h>
#include<stdlib.h>
int main()
{
int N, i;
int* set;
scanf_s("%d", &N);
set = (int*)calloc(N, sizeof(int));
for (i = 0; i < N; i++)
{
scanf_s("%d", (set+i));
}
for (i = 0; i < N; i++)
{
printf("%d", *(set + i));
}
return 0;
}
As mentioned earlier, the int array works perfectly fine but I still want to fix the warning.
Anyways the output for char array is just 'a' and new lines when I enter "a b c" as input and hit enter, Alternatively I tried entering just 'a' and hitting enter and it doesn't even let me input the other characters anymore.
I want to understand what exactly is wrong and want to fix it. The current IDE I'm using is VS but I'd like a gcc 6.3 compatible version as well.
Edit: The error I'm getting is on the printf line and it reads-
Warning C6011 Dereferencing NULL pointer 'set+i'.
The primary difference between the int version that works and the char version that doesn't is that you use %d and %c — and %d skips white space but %c does not.
Change the "%c" to " %c" and you're in with a fighting chance.
Three scanf() — or scanf_s() if you're working on Windows — conversions do not skip white space. They are %c, %[…] (scan sets), and %n.

counting the number of brackets using array

I am new to coding and would really appreciate if you could help me with this question. I can't find out why my code does not give me the correct result. Thank you for your time!!
Q:
Using a first dimensional array, count the number of closing brackets and open brackets. Input must be in one line.
Ex. Input: (()))
Output: 3 2
I used an array to receive the input in one line and the for loop to count the number of opening/closing brackets.
#include <stdio.h>
int main(){
char str[1000]; int l=0;r=0;
printf("Enter:\t");
gets(str);
int length=sizeof(str)/sizeof(str[0]);
for(int i=0;i!=EOF && i<length;i++)
{
if(str[i]=='(')
l++;
else if(str[i]==')')
r++;
}
printf("%d %d",l,r);
}
Expected
Input: (())
Output: 2 2
What I get
Input: (())
Output: 6 2
i!=EOF is not needed as this is not a file
int length=sizeof(str)/sizeof(str[0]) doesnt give the length of the string strlen() from #include <string.h> does
your loop is wrong (actually your conditions)
for(size_t i = 0; i < strlen(str);i++)
{
if(str[i]=='(')
{
l++;
}
if(str[i]==')')
{
r++;
}
}
There are mistakes which are covered in basic C learning.
sizeof(str)/sizeof(str[0]); returns size of str array which is in your case 1000. To get length of user input, use strlen function: int length = strlen(str).
Later, use your for loop as for(int i=0;i<length;i++) or better:
//Include string.h on beginning of file
#include <string.h>
size_t length = strlen(str);
for (size_t i = 0; i < length; i++) {
//Do your if.
}
You also have a syntax error at the declaration of r.
You would either have int l=0,r=0;
Or
Int l=0;
Int r=0;
Although, the compiler should have warned you about this.

Concatenate all input strings [ C programming ]

I am new to c programming and would like to write a program which has the following requirement:
Input: The number of inputs n, then n input chars , for example, 3 welcome to hku
Output concatenated chars, for example, welcomehku
However, I discovered a problem that when I submit the codes as following to the c autochecking platform, the output is ~~~~welcometohku instead of welcometohku.
Would anyone like to give help on the issue? Thank you very much to all of you.
#include<stdio.h>
#include<string.h>
int main(){
int num; /* array with 50 elements */
int i = 0;
char iarray1[100];
/* read array */
scanf("%d", &num);
char iarray[num][100];
for (i = 0; i < num; i++) {
scanf("%s", iarray[i]);
}
/* print array elements in reverse order */
for (i = 0; i < num; i++) {
strcat(iarray1,iarray[i]);
}
//display the concatenated string
printf("%s",iarray1);
return 0;
}
You need to initialize iarray1
Try
char iarray1[100] = {0};
The reason is that an uninitialized iarray1 may contain any value. So when you do the first strcat it may happen the string you want to concatenate is appended to some gargabe value.

I'm getting runtime error in this program...why?

A program for merging two words:
#include<stdio.h>
int main()
{
char s1[10],s2[10],s3[10];
int i,j,n=1;
for(i=0;i<n;i++)
scanf("%s",&s1[i]);
for(i=0;i<n;i++)
scanf("%s",&s2[i]);
for(j=0;s2[i];j++)
{
s3[i] = s1[i]+s2[j];
}
printf("%s",s3);
return 0;
}
I'm getting a runtime error in this program. Could anyone help me to correct it or point out what the error is?
for(i=0;i<n;i++)
scanf("%s",&s1[i]);
for(i=0;i<n;i++)
scanf("%s",&s2[i]);
This is not how you read strings. Try this:
scanf("%s", s1);
scanf("%s", s2);
That's not perfect, but should work for a beginner.
scanf("%s",&s1[i]); does not do what you think it does. It seems to me you are confusing %s with %c. This is causing a buffer overflow. So read the documentation of scanf() format strings.
Then, don't use scanf() because it's unsafe and hard to use correctly. For getting user input, use fgets().
Your code have several problems:
You are using scanf in a wrong a way. It should be like scanf("%s", s1); same for s2.
To merge two strings you can use built-in function strcat which append its second argument to its first argument; just use it two times to merge your two strings in vector s3.
In conclusion, your code should look like:
#include<stdio.h>
#include <string.h>
int main()
{
char s1[10],s2[10],s3[20];
scanf("%s",s1);
scanf("%s",s2);
strcat(s3,s1);
strcat(s3,s2);
printf("%s",s3);
printf("\n");
return 0;
}
Just remember that your s3 vector must be sufficiently large to contain both your strings.
#include <stdio.h>
int main(void){
char s1[10], s2[10], s3[20];
int i, j, n=1;
scanf("%9s", s1);
scanf("%9s", s2);
sprintf(s3, "%s%s", s1, s2);
printf("%s\n",s3);
return 0;
}
You're probably doing a free online course "Programming, Data Structures & Algorithms" at https://onlinecourses.nptel.ac.in
Anyway, the answer to this is:
#include <stdio.h>
#include <string.h>
int main() {
char a[20], b[10], c;
int x[20];
int i,j,l,n,swap;
scanf("%s",a);
scanf("%s",b);
strcat(a,b);
l=strlen(a);
for(i=0; i<l; i++) {
n = a[i];
x[i] = n;
}
for(i=0; i<(l-1); i++) {
for(j=0; j<(l-i-1); j++) {
if(x[j]>x[j+1]) {
swap = x[j];
x[j] = x[j+1];
x[j+1] = swap;
}
}
}
for(i=0; i<l; i++) {
c = x[i];
printf("%c",c);
}
}
You should edit the question if you really meant this.
Okay first of all, if you declare like char arr[10]; then read like scanf("%s",arr);
So you read the two words like:
scanf("%s",s1);
scanf("%s",s2);
Okay, now to merge two words of length 10, first declare the result array to be twice of 10.
So here goes the full code:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int compare (const void * a, const void * b)
{
return ( *(char*)a - *(char*)b );
}
int main()
{
char s1[10],s2[10],s3[20];
scanf("%s",s1);
scanf("%s",s2);
strcpy(s3,s1); // copies content of s1 to s3
strcat(s3,s2); // merges to end of s3 the content of s2
qsort(s3,strlen(s3),sizeof(char),compare); //sorts s3
printf("%s",s3);
return 0;
}
See qsort().

infinite loop on printing 2D array

#include <stdio.h>
void main()
{
char plaintext[50];
char key[20];
int plain=0,max1=0,max2=0; // max2 amount of coloumn n max1 for row on chip
char chip[30][30];
int i,j,k=0,c=0;
printf("Enter key :");
scanf("%s",&key);
for(i=0;key[i]!='\0';i++)
{
max2++;
}
printf("Enter plaintext :");
scanf("%s",&plaintext);
for( i = 0; plaintext[i] != '\0'; i++ )
{
plain++;
}
if (plain%max2==0)
max1=plain/max2;
else
max1=plain/max2+1;
while(plaintext[k]!='\0')
{
for (i=0;i<max1;i++)
{
for (j=0;j<max2;j++)
{
chip[i][j]=plaintext[k];
k++;
}
}
}
printf("%s",chip[0][0]);
}
1st im trying to move the string on plain (1D array) into chip(2d array) with dynamic array on the 2D but when im trying to run this code it show nothing than stopped working.. is there anything goes wrong with my 2D array?
I compiled it on Linux (after omitting the void because in Linux main has to return a value) and I got "Segmentation fault". I guess it is because of printf("%s",chip[0][0]);, it should be printf("%s",chip[0]);
I mean chip[0][0] returns a specific character in the chip[0] and you want to print the first string in chip array, right?

Resources