Printing arrays with strings in C [closed] - c

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I was just wondering if someone knows why my while statement I have is not printing out the array that the user is filling in. Below I have attached my code. Thanks so much for your help!
/*
* File: strings.c
*
* Purpose: To create a small program that should read in 2 strings from the
* user, “string1” and “string2”, each of which can NOT be longer
* than 79 characters.
*/
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char** argv) {
// Prints the length of each string (i.e. how many characters each string contains).
const int LENGTH_OF_STRING = 79;
char firstText[LENGTH_OF_STRING + 1 ];
char secondText[LENGTH_OF_STRING + 1 ];
int charPosition = 0;
// Ask user to type in first string
printf("Please enter your first string no longer than %d characters: \n", LENGTH_OF_STRING);
scanf("%[^\n]s", firstText);
fgetc(stdin);
// Ask user to type in second string
printf("Please enter your first string no longer than %d characters: \n", LENGTH_OF_STRING);
scanf("%[^\n]s", secondText);
fgetc(stdin);
// The computer need to print out the users first string
while ((charPosition !=0) && (charPosition < LENGTH_OF_STRING + 1 )){
printf("%c", firstText[charPosition]);
charPosition ++;
}
return (EXIT_SUCCESS);
}

You initialize charPosition at 0 and then test that charPosition does not equal zero in your while loop. The loop is never entered.
Your condition should be:
while ((firstText[charPosition] != '\0') && (charPosition < LENGTH_OF_STRING + 1)) {
If you just had the latter test you would print every character in your buffer, even after the null terminator.

Related

How to write a C program that reads a user input strings and prints only those are not ‘a-z’ or ‘A-Z’ [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I am trying to create a program that reads a user input strings and prints only those are not ‘a-z’ or ‘A-Z’. The following program can print string of characters. But how do I write a C program that reads a user input strings and prints only those are not ‘a-z’ or ‘A-Z’? I appreciate any help that I can get.
#include <stdio.h>
int main()
{
char name[30];
printf("Enter name: ");
gets(name); // read string
printf("Name: ");
puts(name); // display string
return 0;
}
To start with... Never use gets (nor scanf("%s" …). Use fgets.
Then you just to iterate over the string and check if the individual character is in the range of characters you don't want to print.
#define MAX_LEN 30
int main()
{
char name[30];
printf("Enter name: ");
if (fgets(name, MAX_LEN, stdin) != NULL)
{
int i = 0;
while (name[i])
{
if ((name[i] < 'a' || name[i] > 'z') &&
(name[i] < 'A' || name[i] > 'Z'))
putchar(name[i]);
++i;
}
}
return 0;
}
Input:
12john34BEN56 78Al9
Output:
Enter name: 12john34BEN56 78Al9
123456 789

Printf prints more character than those contained in my string [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I have to write a program that acts like a shell. I wrote the function that gets the input from the user. I also wrote the function that splits it into arguments. The first time I type something, it works well, but the second time, it prints different characters after the ones that I gave it. I don't have to print it in the program. I was just doing it to see if it works correctly. I read a bunch of stuff online, but I can't figure out my error. I suppose it is in makeArgs(), but I can't pinpoint it.
Also, when I give it an input, the readline function adds a \n at the end of the string. I suppose it is from the fact that I press the enter key. I managed to solve the issue, by manually replacing it, but I would like to know if it is normal.
Any help really be appreciated.
Thank You
Screenshot of Xterm after 2 inputs.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int getText();
int makeArgs();
char *textEntre;
size_t nbCharacters;
char **arguments;
int main (void)
{
while (1){
getText();
int nbArguments = makeArgs();
for(int i =0; i<5; i++){
printf("%s \n",arguments[i]);
}
for(int i=0; i<nbArguments; i++){//free the char ptrs at the end
free(arguments[i]);
}
}
free(textEntre);
free(arguments);
return 0;
}
int getText(){
size_t buffersize = 0;
nbCharacters = getline(&textEntre, &buffersize, stdin);
textEntre[nbCharacters-1] =' '; // when I press enter it regiter the enter as \n so I replace it with a space
return 0;
}
int makeArgs(){
arguments = (char **)malloc(sizeof(char*)*20);
int i;
int j = 0;
int k = 0;
int nbElem = 20; //the number of ptrs that can be in arguments
for(i = 0; i<nbCharacters; i++){
if(i == 20){ //increases the memory allocated if there are more than 20 arguments
nbElem = nbElem *2;
arguments = (char **)realloc(arguments, sizeof(char*)*nbElem);
}
if(textEntre[i] == '"'){ //checks for ""
i++;
while(textEntre[i] != '"'){
i++;
}
}
if(textEntre[i] == ' ' && textEntre[i-1] == ' '){ // eliminates useless spaces
j++;
}
else if(textEntre[i] == ' '){ //save a single argument
char * chptr;
chptr = (char *)malloc(i-j+1); //giving +1 for the \0 at the end
strncpy(chptr, &textEntre[j], i-j);
arguments[k] = chptr;
k++;
j = i +1;
}
}
return k;
}
chptr = (char *)malloc(i-j+1); //giving +1 for the \0 at the end
You properly allocated memory for that terminating \0, but where do you actually add that "\0 at the end"?
strncpy(chptr, &textEntre[j], i-j);
strncpy does not necessarily zero-terminate the destination buffer. You have to do it yourself.
In fact, in this specific application strncpy is a rather inappropriate function: it does not give you anything over ordinary memcpy and might be less efficient. You could just do
memcpy(chptr, &textEntre[j], i - j);
with potentially better efficiency. And, again, don't forget to zero-terminate the destination buffer.
Or you can use sprintf for the same purpose as follows
sprintf(chptr, "%.*s", i - j, &textEntre[j]);
which will produce a properly zero-terminated string in the destination. (Albeit you won't see sprintf used that way very often.)

Use of fgets in c [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I need to write a program which converts a number from one base to another.
i need to get a user input in the form of: <original base><new base><number in original base>
I’m not allowed to use scanf and also im not allowed to assume the size of the line.
I have already tried using fgets() but I don’t know how to use it without limiting the size. I would love to get some ideas of what to do. Thanks.
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int BaseChanger()
{
char input[12];
printf("enter the original base, new base ,number");
fgets(input, 12, stdin);
}
You can use this snippet as a form of getline
int max= 100;
char* array;
array = malloc(max*sizeof(char));
if(array == NULL)
exit(1);
int c,i=0;
while( ( c = getchar()) != EOF && c != '\n' && i < max ) {
array[ i++ ] = c ;
if( i == max)
{
char * narray = realloc(array, max *= 2);
if( narray == NULL ){
free(array);
exit(1);
}
array = narray;
}
...
}
Once you do this, extract the numbers and then do the rest of the logic.

Trouble with C program blank output [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
int i=0,j=0;
char string[100], string2[100];
scanf("%s",&string);
while (string[i]!='\0'){
if(string[i]=='a' || string[i]=='e' || string[i]=='i' || string[i]=='o' || string[i]=='u' || string[i]=='A' || string[i]=='E' || string[i]=='I' || string[i]=='O' || string[i]=='U'){
string[i]=string2[j];
}
string[i] = tolower(string[i]);
string[i] = string2[j];
string2[j-1]='.';
}
printf("%s", string2);
return 0;
The question is entering a word and then removing all vowels, adding '.' after every constant and making all upper case letters lower case.
Since string is an array, you don't use & when passing it to scanf(), this gives you a double pointer and is an error. Any time you find yourself with a 10 clause if statement, you're just asking for problems (e.g. easy to get tripped up by typos.) You can simplify this test with index() and a string containing all the vowels. It wouldn't hurt to comment as you write your code to indicate which of the requirements each section implements. The i variable needs to be incremented every time through the loop, the j variable needs to be incremented every time a new character is added to string2. After the scanf(), you shouldn't be assigning into string, treat it as readonly, only assign into string2. And j-1 shouldn't happen. Finally, since string2 isn't intialized, there may be garbage in it and you haven't null terminated it. Putting it all together:
#include <ctype.h>
#include <stdio.h>
#include <strings.h>
#define VOWELS "AEIOUaeiou"
int main()
{
char string[100], new_string[100] = { 0 };
// enter a word
scanf("%s", string);
for (int i = 0, j = 0; string[i] != '\0'; i++)
{
// remove all vowels
if (index(VOWELS, string[i]) == NULL)
{
// make all upper case letters lower case
new_string[j++] = tolower(string[i]);
if (isalpha(string[i]))
{
new_string[j++] = '.'; // add '.' after every consonant
}
}
}
printf("%s\n", new_string);
return 0;
}
I'm assuming "after every constant" was meant to read "after every consonant", otherwise please clarify what you mean by constant.

Terminating a program using carriage return in C [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
Quesion: Write a C program that will accept a line of text. Store it in an array & then write it out backwards. Allow the length of line to be unspecified terminated by carriage return but assume it will not exceed 80 characters
My Solution:
#include <stdio.h>
int main()
{
printf("\nEnter a sentence:\n");
char sent[80]; // creates an array of length 80
int i = 0;
while((sent[i] = getchar()) != '\n')
{
i++;
}
sent[i] = '\0';
printf("The Reversed sentence is : ");
for(i=i-1; i>=0; i--)
{
printf("%c", sent[i]);
}
getchar();
scanf("%c", &sent[i]);
return 0;
}
Is my code correct?
(I was wondering about carriage return part)
What if you enter exactly 80 characters??? You will end up putting '\0' at sent[81], which is very bad...
sent[80] will be the '\n' and sent[81] the '\0'
Also I am not sure why you do
getchar();
scanf("%c",&sent[i]);
at the end of your function. i at this point is -1.

Resources