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
Related
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);
}
I am trying to take a user inputted string and look at each code to see if it appears in another string of strings. So far my code works.
If the word is successfully found then the alpha representation is to be added to an array that will eventually be printed, but only if all codes were found.
I am having issues with what gets stored in my array that is going to be printed.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef char *string;
typedef char *alpha;
int main(void)
{
string morse[4]={".-", "-...","----.", ".."};
string alpha[4]={"A", "B", "9", "I"};
char prntArr[50];
char *input;
char *hold;
input = malloc(200);
hold = malloc(50);
int i=0;
int j=0;
int ret;
int x;
int w=0;
int z=0;
printf("please enter a string\n");
scanf("%[^\n]",input);
do{
if (input[i] !=' ')
{
hold[j] = input[i];
j++;
}
else
{
hold[j]='\0';
for (x=0;x<4;x++)
{
printf("value of x %d\n",x);
ret = strcmp(morse[x], hold);
if (ret==0)
{
printf("%s\n",alpha[x]);
prntArr[w]=*hold;
w++;
x=4;
}
else
{
ret=1;
printf("invalid Morse code!");
}
}
j = 0;
}
i++;
}while(input[i] !='\0');
for (z=0;z<50;z++)
{
printf("%c",prntArr[z]);
}
return 0;
free(input);
}
The problem you asked about is caused by the way prntArr is used in the program. It really should be an array of character pointers into the alpha array. Instead, it's manipulated as an array of characters into which the first character of each morse code element is stored. And when it's printed, the variable that tracks how much of the array is used is simply ignored.
Another problem is that your code uses spaces to break the codes but there won't necessarily be a space at the end of the line so a code might get missed. In the program below, I switched out scanf() for fgets() which leaves a newline character on the end of the input which we can use, like space, to indicate the end of a code.
Other problems: you print the invalid Morse code message at the wrong point in the code and you print it to stdout instead of stderr; you remember to free input but forget to free hold; you put code after return that never gets called.
Below is a rework of your code that addresses the above problems along with some style issues:
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
int main(void)
{
char *morse[] = {".-", "-...", "----.", ".."};
char *alpha[] = {"A" , "B" , "9" , "I" };
char *print_array[50];
int print_array_index = 0;
char hold[50];
int hold_index = 0;
char input[200];
int i = 0;
printf("please enter a string: ");
fgets(input, sizeof(input), stdin);
while (input[i] !='\0') {
if (input[i] ==' ' || input[i] == '\n')
{
hold[hold_index] = '\0';
bool found = false;
for (int x = 0; x < sizeof(morse) / sizeof(char *); x++)
{
if (strcmp(morse[x], hold) == 0)
{
print_array[print_array_index++] = alpha[x];
found = true;
break;
}
}
if (!found)
{
fprintf(stderr, "invalid Morse code: %s\n", hold);
}
hold_index = 0;
}
else
{
hold[hold_index++] = input[i];
}
i++;
}
for (int x = 0; x < print_array_index; x++)
{
printf("%s ", print_array[x]);
}
printf("\n");
return 0;
}
SAMPLE RUNS
> ./a.out
please enter a string: ----. -... .- ..
9 B A I
>
> ./a.out
please enter a string: .- --- ..
invalid Morse code: ---
A I
>
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.
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.
This is the error I am getting:
test.c:110:21: error: expected expression
else if(isupper(p_i))
^
1 error generated.
In an else if statement towards the end of the code—"else if(isupper(p_i))"—the error is generated.
I have commented above this 'else if' statement. Please let me know what's wrong. Thank you.
#include <stdlib.h> // The library which contains the 'atoi()' function
#include <stdio.h> //
#include <cs50.h> // typedef char *string; and GetString()
#include <string.h> //
// 'argv[]' is an array of strings. (Fun fact: A string is an array of characters.)
// 'argc' is the integer variable which stores the number of strings that are in 'argv[]'.
int main(int argc, string argv[])
{
// VARIABLE DECLARATIONS
int k; // Integer variable for the non-negative, encryption key
string plaintext; // Variable to store the information to be encrypted
int n; // Integer variable for the string length
string ciphertext = NULL; // Variable to store the encrypted information
// This loop analyzes the command-line argument(s): We need exactly one argument (i.e. argc = 2)
if (argc > 2)
{
printf("\n");
printf("Too many arguments. Please try again.\n");
return 1;
}
else if (argc < 2)
{
printf("\n");
printf("This program requires that you provide an argument. Please try again.\n");
return 1;
}
else if (argc == 2)
{
k = atoi(argv[1]);
if (k == 0 || k < 0)
{
printf("\n");
printf("Invalid input: encryption key needs to be a non-negative integer.\n");
return 1;
}
}
// Prompt the user for a string input to be encrypted:
printf("\n");
printf("Please enter the information to be encrypted:\n");
plaintext = GetString();
n = strlen(plaintext);
printf("n = %d \n", n);
// We need to implement Caesar's Cipher algorithm:
// But first, we select for alphabets only by using the 'isalpha()' function:
for (int i = 0; i < n; i++)
{
int p_i = plaintext[i];
int isalpha(int p_i);
if (isalpha(p_i))
{
int islower(int p_i);
if (islower(p_i))
{
printf("Caesar's algorithm for the lower case goes here.\n");
}
int isupper(int p_i);
//-----------------------------------------------------------
// THE FOLLOWING else if STATEMENT IS THE SOURCE OF THE ERROR
//-----------------------------------------------------------
else if(isupper(p_i))
{
printf("Caesar's algorithm for the upper case goes here. \n");
}
}
else
{
for (int j = 0; j < n; j++)
ciphertext[i] = plaintext[i];
}
}
// Program terminates
return 0;
}
You have a function prototype between the if and the else:
if (islower(p_i))
{
printf("Caesar's algorithm for the lower case goes here.\n");
}
int isupper(int p_i);
//-----------------------------------------------------------
// THE FOLLOWING else if STATEMENT IS THE SOURCE OF THE ERROR
//-----------------------------------------------------------
else if(isupper(p_i))\
The else block must follow immediately after the if block. If you had put the line int isupper(int p_i); pretty much anywhere else (before the first time you use it), you would not have this error. Even better, you should load this prototype via #include <ctype.h> at the top of your file.
int isupper(int p_i);
//-----------------------------------------------------------
// THE FOLLOWING else if STATEMENT IS THE SOURCE OF THE ERROR
//-----------------------------------------------------------
else if(isupper(p_i))
Remove this declaration: int isupper(int p_i);.
Use the correct #include directive at the top of your source file to declare isupper function:
#include <ctype.h>
You cannot use any statement between if and else statement. Example -
if()
{
//some code
}
//some Code ---> This is wrong //this should not be in between if and else
else
{
//some code
}
Your function prototypes:
int islower(int p_i);
int isupper(int p_i);
do not belong within the main() function (or any function) - though that's technically legal which is why the first is not causing a problem.
However, they cannot live within an 'if / else' construct - you have the second sandwiched between an if clause and an else clause.
The best solution is to put them at the head of the file, or better just use:
#include <ctype.h>
to get the relevant header file with the prototypes in included, then remove the prototypes from the function.