array of string output is a clover symbol - c

No matter what the 5th input the output was clover symbol, program purpose was to align right the inputs:
EDIT
im not using scanf(%[\^n],a[i]), the output was horrible, using gets instead
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char a[6][50];
int i;
for (i=1;i<=5;i++)
{
printf("insert name%d :\n",i);
gets(a[i]);
}
for (i=1;i<=5;i++)
{
printf("%d%25s\n",i,a[i]);
}
return 0;
}
Example output:
1 far cry
2 iron man
3 new super mario
4 program
5 "clover"

Using your code, I got strange chars on output as you mentioned.
So, I made some fixes on your code and now I think it works properly.
#include <unistd.h>
int main(void)
{
char a[6][50];
int i, r;
for (i = 1; i <= 5; i++) {
printf("insert name%d :\n", i);
r = read(STDIN_FILENO, a[i], 49);
a[i][r] = '\0';
}
for (i = 1; i <= 5; i++) {
printf("%d%25s\n", i, a[i]);
}
return 0;
}
Avoid to use deprecated functions in your code.
You need to ensure that after reading from stdin, your buffer is going to get the null terminator right after the last position written in buffer.

Related

Printing Staircase pattern using only one loop

enter image description here
I thought about printing this shape only using one loop but I didn't make it and I want to know if it's possible and if it's possible what should I do ?
Here is my code:
#include <stdio.h>
int main() {
int i;
for (i = 1; i <= 16; i++) {
if (i % 4 == 0) {
printf("\n");
printf(" ");
}
else
printf("*");
}
}
Having only allowing one for loop for the task seems like an artificial constraint, but with that in mind, utilizing some string functions would allow you to perform that task. Following is a snippet of code utilizing just one for loop.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 24
int main()
{
char gap[MAX];
char * stair = "***";
strcpy(gap, "");
for (int i = 0; i < (MAX / 3) - 1; i++)
{
printf("%s%s\n", gap, stair);
strcat(gap, " ");
}
return 0;
}
Following was the sample output at the terminal.
#Dev:~/C_Programs/Console/Stairs/bin/Release$ ./Stairs
***
***
***
***
***
***
***
See if that meets the spirit of your project.

How to find duplicate letter in array in C

I am making a program which requires the user to input an argument (argv[1]) where the argument is every letter of the alphabet rearranged however the user likes it. Examples of valid input is "YTNSHKVEFXRBAUQZCLWDMIPGJO" and "JTREKYAVOGDXPSNCUIZLFBMWHQ". Examples of invalid input would then be "VCHPRZGJVTLSKFBDQWAXEUYMOI" and "ABCDEFGHIJKLMNOPQRSTUYYYYY" since there are duplicates of 'V' and 'Y' in the respective examples.
What I know so far is, that you can loop through the whole argument like the following
for (int j = 0, n = strlen(argv[1]); j < n; j++)
{
//Place something in here...
}
However, I do not quite know if this would be the right way to go when looking for duplicates? Furthermore, I want the answer to be as simple as possible, right know time and cpu usage is not a priority, so "the best" algorithm is not necessarily the one I am looking for.
Try it.
#include <stdio.h>
#include <stddef.h>
int main()
{
char * input = "ABCC";
/*
*For any character, its value must be locate in 0 ~ 255, so we just
*need to check counter of corresponding index whether greater than zero.
*/
size_t ascii[256] = {0, };
char * cursor = input;
char c = '\0';
while((c=*cursor++))
{
if(ascii[c] == 0)
++ascii[c];
else
{
printf("Find %c has existed.\n", c);
break;
}
}
return 0;
}
assuming that all your letters are capital letters you can use a hash table to make this algorithm work in O(n) time complexity.
#include<stdio.h>
#include<string.h>
int main(int argc, char** argv){
int arr[50]={};
for (int j = 0, n = strlen(argv[1]); j < n; j++)
{
arr[argv[1][j]-'A']++;
}
printf("duplicate letters: ");
for(int i=0;i<'Z'-'A'+1;i++){
if(arr[i]>=2)printf("%c ",i+'A');
}
}
here we make an array arr initialized to zeros. this array will keep count of the occurrences of every letter.
and then we look for letters that appeared 2 or more times those are the duplicated letters.
Also using that same array you can check if all the letters occured at least once to check if it is a permutation
I don't know if this is the type of code that you are looking for, but here's what I did. It looks for the duplicates in the given set of strings.
#include <stdio.h>
#include <stdlib.h>
#define max 50
int main() {
char stringArg[max];
int dupliCount = 0;
printf("Enter A string: ");
scanf("%s",stringArg);
system("cls");
int length = strlen(stringArg);
for(int i=0; i<length; i++){
for(int j=i+1; j<length; j++){
if(stringArg[i] == stringArg[j]){
dupliCount +=1;
}
}
}
if(dupliCount > 0)
printf("Invalid Input");
printf("Valid Input");
}
This code snippet is used to count the duplicate letters in the array.
If you want to remove the letters, Also this code snippet is helpful .Set null when the same characters are in the same letter.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int count=0;
int array[]={'e','d','w','f','b','e'};
for(int i=0;i<array.Lenth;i++)
{
for(int j=1;j<array.Length;j++)
{
if(array[i]==array[j])
{
count++;
}
}
}
printf("The dublicate letter count is : %d",count);
}

Error in c when iterating: use of undeclared identifier i

I am creating a program that will ask a command line argument from the user, and the user need to input only integers as the argv[1]. It should reject any input other than integers. My code is as below:
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
int main(int argc, string argv[] )
string s = argv[1];
for (int i = 0; n = strlen(s); i< n; i++)
{
if(!( isdigit(s[i])) )
{
printf("All numbers: correct input");
return 1;
}
}
//Else print a prompt asking for a plaintext to cipher
else
{
string p = get_string("Your text here: ");
return 0;
}
}
Running the above code throws me an error: error: use of undeclared identifier 'i' for (int i = 0; n = strlen(s); i< n; i++)
Where do I do wrong here and how do I fix this? Thanks.
Sorry if my questions seem stupid, I am still a newbie learning here and know absolutely nothing about C before. Thanks for the help though.
If you have a C89 compiler you will need to put the delarations at the top of the scope block, so the variable i has to be declared before the for loop.
Try this if your using C89:
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
int main(int argc, string argv[] ){
string s = argv[1];
int i = 0;
int n = strlen(s);
for (; i< n; i++)
{
if(!( isdigit(s[i])) )
{
printf("All numbers: correct input");
return 1;
}
}
//Else print a prompt asking for a plaintext to cipher
else
{
string p = get_string("Your text here: ");
return 0;
}
} //end of for loop? TODO: fix your braces spacing the sample was broken
}//end of for main? TODO: fix your braces spacing the sample was broken

How to incorporate an input array in this program

This is a code that has to take an input array from the user and input the same after removing the duplicates. However, I am unsure on how to incorporate an input array in this, and right now it has the elements hardcoded. This is my first week of programming so I apologize if this is a silly question. This is the code:
#include <stdio.h>
#include <stdbool.h>
#define nelems 8
int main()
{
int l[nelems] = {1,2,3,1,4,4,5,6};
for(int m=0;m<nelems;m++)
{
bool wase = 0;
for(int n=0;n<nelems && m>n;n++)
{
if (l[m] == l[n] && m != n)
wase = 1;
}
if (wase == 0){
printf("%d\n", l[m]);
}
}
return 0;
}
Try using a for loop and scanf.
int i;
for(i=0;i<nelems;i++){
scanf("%d",&l[i]);
}
This is what you need.
#include <stdio.h>
#include <stdbool.h>
#define nelems 8
int main()
{
int i;
int l[nelems] ;
for(i=0;i<nelems;i++)
{
printf("enter %d number :",i);
scanf("%d",&l[i]);
}
for(int m=0;m<nelems;m++)
{
bool wase = 0;
for(int n=0;n<nelems && m>n;n++)
{
if (l[m] == l[n] && m != n)
wase = 1;
}
if (wase == 0){
printf("%d\n", l[m]);
}
}
return 0;
}
If you like int-type array, you can just declare another one:
int input[nelems];
and follow the user968000 advice, remembering that when you are typing the sequence in your console you have to put a white space between each number.
To avoid that, I'd rather use char-type arrays, declared as follows:
char l[nelems] = {'1', '2', '3' /*etc.*/};
char input[nelems];
Then you make a for loop, as user968000 suggested:
int i;
for(i=0;i<nelems;i++)
scanf("%c", &input[i]);
In this case you won't need the white spaces between the digits. Notice the '&' character in the scanf function: just put it as I showed, you'll surely learn what it is in next lessons.
So you have an input array and you can handle it as you want.

How to count the elements of arrays in C?

#include <stdio.h>
#include <string.h>
int main()
{
char name[32][32];
char input[32];
int number;
int i;
for(i=0;i<10;i++)
{
fgets(input,sizeof(input),stdin);
sscanf(input,%s,name[i]);
}
//assume that we don't know variable name have 10 element of arrays.
//function to count how many elements of arrays to stored at number.
for(i=0;i<number;i++)
{
printf("%s",name[i]);
}
}
What function can count the elements of the arrays?
How about initialising your target strings to 0 then checking if they are not null whilst printing?
#include <stdio.h>
#include <string.h>
int main()
{
char name[32][32] = {0};
...
for(i=0;i<32;i++)
{
if(name[i][0]!='\0')
printf("%s",name[i]);
}
}
This one is a solution.
But i don't know why it is not working while trying to make a array_length function.
#include<stdio.h>
int main(){
int a[]={1,2,3,4,5,6,7,8,9,0};
int len;
len = sizeof(a)/sizeof(*a);
printf("Length is %d\n",len);
return 0;
}
C does not maintain this kind of information. It is up to the developer to implement some way of knowing that the item in the array is valid or not. Typically this is done by selecting an 'invalid value', which is a value that is never going to occur in real data. Another way of doing this is to separately maintain a count.
This is all fine for learning C. If you are doing this for the real world, you would be much better off using data structures like lists. If you are using C++, I would suggest that you learn STL.
Simple C solution would be something like this. The value of "empty" is used to indicate any value which will not occur normally in the input. You can change the #define to any other value you want like "-----" or ".". We begin by initializing the entire array to "empty"
#include <stdio.h>
#include <string.h>
#define MAX_ITEMS 32
#define MAX_LENGTH 32
#define EMPTY "empty"
int main(void)
{
char name[MAX_ITEMS][MAX_LENGTH];
char input[MAX_LENGTH];
int i;
for(i = 0; i < MAX_ITEMS; i++)
{
strcpy(name[i], EMPTY);
}
for(i = 0; i < 10; i++)
{
fgets(input, MAX_LENGTH, stdin);
sscanf(input, "%s", name[i]);
}
for(i = 0; strcmp(name[i], EMPTY) && i < MAX_ITEMS; i++)
{
printf("%s\n", name[i]);
}
return(0);
}

Resources