Output not showing in C - c

I'm writing a code that must identify the letter 't' or 'T' in a word, before or after the middle of it.
If the first half of the word does contain a 't' or a 'T', the program should output a 1. If the first half does not contain the letter 't' or 'T', but the second half does, then the program should output a 2. Otherwise, if there is no 't' or 'T' in the word at all, the program's output should be -1. The word entered will not have more than 50 letters.
#include <stdio.h>
#include <string.h>
int main() {
char word[50];
int i = 0, length, t = 0, T = 0;
scanf("%s", word);
length = strlen(word);
t = word[i] == 't';
T = word[i] == 'T';
while(!t || !T) {
if((t || T) && i <= length / 2) {
printf("%d", '1');
} else if((t || T) && i > length / 2) {
printf("%d", '2');
//}else{
// printf("%d", '-1');
}
i++;
}
return 0;
}
If I enter any word and press enter, nothing is printed. Another thing is that when I remove the comment slashes from the two lines at the bottom, the program goes through an infinite loop.
Could someone please help?

This sounds like a school assignment, so I'll focus on advising/critiquing your code rather than giving a solution.
The first recommendation I have is to use a for loop instead of a while loop. A Rule of thumb in C is to only use a while loop when you actually don't have any idea how many things you need your program to look at.
You already have the length of the string, so set up your for loop to loop exactly once for each character.
Next you need to change how you are using printf. The %d format specifier is for printing integers, but you are passing it '1'. This is not an integer, it is the ascii representation of the symbol 1 (which is actually has the value 49, see the ascii table for more info)
You can either pass printf the value 1, or use the %c specifier, which expects ascii characters.
Better yet, just say printf("1");
That doesn't get you all the way there, but I think it lays the ground work so you can find the solution!

Condition !t || !T has no sense to be used as loop condition ...ask yourself how the loop will end ? you need just to check i is less than length
Second, the assignments t = word[i] == 't'; T = word[i] == 'T'; outside the loop have no sense ...you will be just pointing to the zero index of the string ...you should check all characters
third , the printf lines need to use %d
fourth , you appear not getting the purpose of the program printing inside loop will lead to printing many numbers and you just want to know if there is t or T you need to print single line.you may use variable int result=0; to hold the value you want and print it in the end ...of course you will need using break statement in the if((t || T) && i <= length / 2) and if((t || T) && i > length / 2) because no need for more searching
fifth, you should re-read , re-think , re-code the assignment before going bored and asking about it
sixth, there is a working version by modifying your code but you should try writing a good solution before looking at a solution as it better to solve your problems by yourself
#include <stdio.h>
#include <string.h>
int main() {
char word[50];
int i = 0, length, t = 0, T = 0;
scanf("%s", word);
length = strlen(word);
int result=0;
while( i<length) {
t = word[i] == 't';
T = word[i] == 'T';
if((t || T) && i <= length / 2) {
result=1;
break;
} else if((t || T) && i > length / 2) {
result=2;
break;
}else{
result=-1;
}
i++;
}
printf("%d",result);
return 0;
}

# include <stdio.h>
int main()
{
char name[20];
int age;
int siblings;
int childrens;
printf ("Hello my name is A.I, what is your name? \n");
scanf("%s", &name);
printf("how old are you : \n");
scanf("%d",&age);
printf("how many siblings you have: \n");
scanf("%d", &siblings);
printf("how many children you have: \n");
scanf("%d", &childrens);
printf("so your name is : %s \n", name);
printf("and your age is : %d \n", age);
printf("you have siblings : %d\n", siblings);
printf("so you have childrens : %d\n", childrens);
return 0;
}

Related

Code in C where it prints from 0 to 100 then asks if user wants to see it again

I'm trying to make a program in C where it prints from 0 to 100 then asks the user to print it again. It's not working.
#include <stdio.h>
#include <string.h>
int main()
{
int num;
char resposta[0];
resposta[0] = 's';
num = 0;
do
{
for (int i = 0; i < 100; i++)
{
num += 1;
printf("%i\n", num);
printf("Repetir?s/n\n");
scanf("%c", resposta[0]);
}
} while ((strcmp(resposta[0], "S") == 0) || (strcmp(resposta[0], "s") == 0));
return 0;
}
when declaring an array in C, the number in the brackets [] is not the index number, it is the total number of elements contained within the array. Setting char resposta[0]; means that resposta contains no elements.
This is different from when accessing elements, which uses a zero-index. So running scanf("%c", resposta[0]); is trying to access the first element, but there are zero elements within resposta, so that's likely why this isn't working.
I also figure I should add that it is entirely possible to just create a char variable that is not an array, since it seems you only need the one character. Just do char resposta; without the brackets.
Some more info on Arrays if you're interested: W3Schools
There are many issues.
You have an array that can contains 0 elements which is rather pointless, you want char resposta[1].
But you don't want an array of chars anyway. You're using the %c specifier you need a single char instead of an array of chars.
You're mixing up strings and chars. Change strcmp(resposta[0], "S")==0 to resposta == 'S', provided you have declared char resposta;.
You're asking the user if he wants to start over again in the for loop which is probably not what you want.
Basically you want this (untested code):
int main() {
char resposta;
resposta = 's';
int num = 0;
do {
num = 0;
for (int i = 0; i < 100; i++) {
num += 1;
printf("%i\n", num);
}
printf("Repetir?s/n\n");
scanf("%c", &resposta); // not the useage of the & operator here
} while (resposta == 'S' || resposta == 's');
}
One of the reasons it is not working is that the program stops to ask the user to continue inside the loop. Another failure is that the counter being used is not reset to zero for the second and subsequent runs. Another failure is the scanf format specifier that does not clear the newline out of the input buffer. The next 'get input' will not find an S/s to continue, but will pickup a LF and terminate the loop.
Things can be simplified if they are separated. The interaction with the user is very clearly defined and should be factored-out into its own function:
#include <stdio.h>
int again(void) {
puts( "Repetir? " );
char ch;
return scanf( " %c", &ch ) == 1 && (ch == 'S' || ch == 's' );
}
// Edit: Just noticed the OP title says "0 to 100"
void out(void) {
int i = 0;
while( i <= 100 ) printf( "%i\n", i++ );
}
int main() {
do out(); while( again() );
return 0;
}

Guess a person's secret number between 0 - 100 using binary search

I converted a code that I know how to construct in python in C Language, but everytime I run the program in CodeBlocks, the program crashes! And I have NO idea why this is happening, can someone help me?
The program is suppose to guess a person's number (between 0 - 100), using binary search.
For example, if my number is 66, the program asks if my number is 50, since 66 is higher than 50, the number 50 becomes the lower boundary while 100 remains to be the higher boundary, and so on...
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
int x;
printf("Please think of a number between 0 and 100\n\n");
x = binarysearch();
printf("%d", x);
}
int binarysearch()
{
int hi,lo,guess;
hi = 100;
lo = 0;
char user_inp;
while (1){
guess = round(((hi + lo)/2));
printf("Is your secret number %d?\n\n", guess);
printf("Enter 'h' to indicate the guess is too high. \nEnter 'l' to indicate the guess is too low.\nEnter 'c' to indicate I guessed correctly. \n");
scanf("%c", &user_inp);
if (strcmp(user_inp, "c") == 0){
break;
}
else if (strcmp(user_inp, "h")==0){
hi = guess;
}
else if (strcmp(user_inp, "l")==0){
lo = guess;
}
else{
printf("Sorry, I did not understand your input.");
continue;
}
}
printf("Game over. Your secret number was");
return guess;
}
As per the comments, the problem was very likely the incorrect use of strcmp:
char *string = "fish";
char not_a_string = 'f';
if (0 == strcmp( not_a_string, string ))
...
The character 'f' has ASCII value 0x66. strcmp would blindly use this as a pointer (expecting it to point to a valid string) which would cause a crash as you access memory that's not yours (a segmentation fault).
You would have got away with strcmp( &not_a_string, string ) in this case, but that's good fortune, not correct code.
To compare the user's character input with another character, you can just use a straightforward equality (since they're both really integers):
if ( user_inp == 'c' ) ...
So that's your code fixed, but how did you ever get to run it in the first place? For me GCC immediately complained:
In function 'int binarysearch()': so.cpp:17:29: error: invalid conversion from 'char' to 'const char*' [-fpermissive]
if (strcmp(user_inp, "c") == 0){
and didn't produce an output. It's telling you the same thing I just did (albeit fractionally more cryptically).
Lessons to learn: listen to your compiler's complaints (and make your compiler as complainy as possible)
#pmg also noted:
add a space before the conversion specifier: scanf(" %c", &user_inp)
Without it, every time you hit Enter:
Sorry, I did not understand your input.Is your secret number 25?
ie you get a spurious complaint. But with the space it works as desired.
(I hate scanf, so have no idea why this works ;) )
Your binary search is incorrect, you need to swap the check of 'h' and 'l'.
Because you compare chars and not strings, use == and not strcmp().
You don't need to include <math.h> because guess is an int, so it'll automatically round floats.
You can use getchar() to clear the buffer after the scanf()
You need to declare your function before main (possibly by defining the function before main).
#include <stdio.h>
#include <stdlib.h>
// WITHOUT <MATH.H>
int binarysearch(void);
int main(void)
{
int x;
printf("Please think of a number between 0 and 100\n\n");
x = binarysearch();
printf("%d", x);
return 0; // RETRUN 0
}
int binarysearch(void)
{
int hi,lo,guess;
hi = 100;
lo = 0;
char user_inp;
int flag = 1; // USE FLAG, NOT BREAK AND CONTINUE
while (flag){
guess = ((hi + lo)/2); // WITHOUT ROUND
printf("Is your secret number %d?\n\n", guess);
printf("Enter 'h' to indicate the guess is too high. \nEnter 'l' to indicate the guess is too low.\nEnter 'c' to indicate I guessed correctly. \n");
scanf("%c", &user_inp);
getchar(); // CLEAR THE BUFFER
if (user_inp == 'c'){ // MAKE FLAG 0
flag = 0;
}
// USE '==', NOT STRCMP
else if (user_inp == 'l'){ // YOU NEED TO SWAP 'L' & 'H'
hi = guess;
}
else if (user_inp == 'h'){
lo = guess;
}
else{
printf("Sorry, I did not understand your input.");
}
}
printf("Game over. Your secret number was ");
return guess;
}

Print output just beside the user input

According to the question, The user needs to enter the no of hours the vehicle is parked and the total charge for the hours should get printed beside it.
for example:
I created this simple program
#include<stdio.h>>
#include<math.h>
float calculateCharges(float hurs);
int main()
{
float hours;//total no of hours vehicle is parked
int i;
printf("%s%10s%10s", "Car", "Hours", "Charges");
for (i = 1; i <= 3; i++)
{
printf("\n%d\t", i);
scanf("%f", &hours);
printf("\t%f\n", calculateCharges(hours));
}
getch();
return 0;
}
float calculateCharges(float hurs)
{
float charges;
hurs = ceil(hurs);
if (hurs >= 24) charges = 10;
else
{
if (hurs <= 3) charges = 2;
else
{
hurs = hurs - 3;
charges = 2 + 0.5*hurs;
}
}
return charges;
}
But now every time I enter hours the charges are getting printed below it instead of beside it. As shown in the image:
Is there is a way to consume the newline after scanf? So that charges can be printed beside the scanf?
I have modified my code this way too, but it didn't make any difference.
printf("%s%10s%10s", "Car", "Hours", "Charges");
for (i = 1; i <= 3; i++)
{
printf("\n%d\t", i);
printf("\t%f\n",(scanf("%f", &hours),calculateCharges(hours)));
}
Let me know if the original question is required. I'm using Visual studio 2017 RC.
You can use something like this:
#include <iostream>
#include <windows.h>
//This will set the position of the cursor
void gotoXY(int x, int y) {
//Initialize the coordinates
COORD coord = {x, y};
//Set the position
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
return;
}
void getCursorXY(int &x, int&y) {
CONSOLE_SCREEN_BUFFER_INFO csbi;
if(GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi)) {
x = csbi.dwCursorPosition.X;
y = csbi.dwCursorPosition.Y;
}
}
I found it here.
As already written in one of the answers this solution is not platform independent.
But i guess there are similar solutions on other platforms and you can easy set the cursor on the position you want.
Example usage in your main:
for (i = 1; i <= 3; i++)
{
printf("\n%d\t", i);
scanf("%f", &hours);
gotoXY( 20, i + 1);
printf("\t%f\n", calculateCharges(hours));
}
Workarounds for scanf can be found here.
scanf_s always generates a new line upon enter and unfortunately other user input capturing platform independent functions I know of (getc & getchar) do so too. Anyway on Windows it could be done using _getch() from conio header.
#include <conio.h>
#include <stdlib.h>
#include <stdio.h>
int getIntFromUser()
{
char readCharacters[10];
int index = 0;
for (int currentChar = _getch(); currentChar != '\r'; currentChar = _getch())
{
if (currentChar == EOF)
{
// Some error that shouldn't occour in your simple homework program
}
if (index > 9)
{
// Another possible error case where you would start to write beyond 'readCharacters' array
}
// We might as well disallow anything but digits, enter & backspace (You don't need anything else, do you?)
if ((currentChar < '0' || currentChar > '9') && currentChar != '\b')
{
continue;
}
else if (currentChar == '\b')
{
if (index > 0)
{
// Delete last character
printf("\b \b");
readCharacters[index] = '\0';
--index;
}
}
else
{
printf("%c", currentChar);
readCharacters[index] = currentChar;
++index;
}
}
if (index == 0)
{
// User pressed enter without having entered a number, let's give him a zero then
return 0;
}
readCharacters[index] = '\0';
int retVal = atoi(readCharacters);
// Worth noting that the value of converted user given string shouldn't be greater than what a signed int can hold
return retVal;
}
int main(int argc, char* argv[])
{
// Unlike scanf_s this will not generate a new line on enter
printf("getIntFromUser() sample (enter a number)\n");
int someValue = getIntFromUser();
printf(" -- This will be printed on the same line. (someValue is %d)\n\n", someValue);
// scanf_s sample
int anotherValue;
printf("scanf_s() sample (Insert a number.)\n");
scanf_s("%d", &anotherValue);
printf("This will be printed on a new line\n\n");
printf("Press any key to exit.");
_getch();
return 0;
}
EDIT
I feel like the above would become less readable if I were to add a comment over every code line. Instead I'm going to paste some blocks of code 1 by 1.
But first about the _getch function: It waits for the user to type something into the console and then returns the user given char as an int. char implicitly converts to int, so you may compare the _getch result to a character as I did many times in getIntFromUser (e.g. if (currentChar == '\b') { ... }).
You should also know about the values a char can hold and what their values are as an int (check out http://en.cppreference.com/w/cpp/language/ascii).
Going by the table the char '0' would be value 48 as an int, which is what _getch would return if the user were to type a 0.
First declare an array/string of 10 elements. Hope you know about them already. In this case the array is basically a chain of 10 elements that are all of type char, which are also referred to as string.
char readCharacters[10];
An indexer for the string is required.
int index = 0;
Below we have the usual for loop that...
1st: creates a variable of type int and assigns the result of _getch to it.
2nd: will determine if the loop shall keep executing. In this case the loop will break when currentChar is not '\r', which is an escape sequence that represents enter as a character.
3rd: will execute stuff inside once and then update currentChar with a new _getch.
for (int currentChar = _getch(); currentChar != '\r'; currentChar = _getch())
Checks if the user input (retrieved via _getch) is smaller than '0' (value 48 as an int) and greater than '9' (value 57 as an int). If either of them is true it will additionally check if the value of currentChar is not '\b' (value 8 as an int), which is the escape sequence for a backslash.
When that additional check evaluated to true as well then the keyword continue is used. Meaning that the rest of the block in the loop is not executed and instead the loop will start at the top again by getting a new user input and evaluating if the loop is to be continued by checking if obtained currentChar was enter.
if ((currentChar < '0' || currentChar > '9') && currentChar != '\b')
{
continue;
}
NOTE: You might want to read the comments on the else statement before you read these.
When the above if statement was false we get to the next if-statement (actually else if) that we see below.
As mentioned above: '\b' is backslash and if this is the user given char as well as string/array index being greater than 0 we move one character backwards in the console by "printing" '\b' and then write an empty character in order to delete what was written at that place previously. That puts us back to the position we were before so we print another backslash. At this point you might wonder why not just go back to the previous line that scanf_s causes, but that won't work. We must also not forget to replace the last string character with a null terminator and then set the index back by 1.
else if (currentChar == '\b')
{
if (index > 0)
{
// Delete last character
printf("\b \b");
readCharacters[index] = '\0';
--index;
}
}
When we hit this point we know that currentChar is something between 48 and 57 ('0' and '9').
_getch told the program what the user's input was, but we cannot see it in the console unless we print it there. So let's do that.
Also append the user's given character to the string as well as incrementing the index by 1.
else
{
printf("%c", currentChar);
readCharacters[index] = currentChar;
++index;
}
Lastly we call the atoi function that will convert our string/array to an integer.
int retVal = atoi(readCharacters);

Number guessing what the user has in mind C

I'm trying to create a program where the program guesses what kind of number the user has in mind. First it will ask the user for a minimum and maximum number, for example 1 and 10(the number I have in mind should be between 1 and 10 then).
Lets say I have the number 4 in mind and the program will output a number. I can type in L for low, H for high or G for good.
If I type in L, the program should generate a number lower than the guessed number, for H it should guess an higher number. If I input G, the program should stop and print out how many times it guessed.
I have added my code below, what am I missing?
#include <stdio.h>
#include <stdlib.h>
int main() {
int minNumber;
int maxNumber;
int counter;
printf("Give min and max: ");
scanf("%d %d", &minNumber, &maxNumber);
//printf("%d %d", minNumber, maxNumber);
int num_between_x_and_y = (rand() % (maxNumber - minNumber)) + minNumber;
char input[100];
do {
printf("is it %d? ", num_between_x_and_y);
scanf("%s", input);
if (input == 'L') {
counter++;
}
if (input == 'H') {
counter++;
}
} while (input != 'G');
printf("I guessed it in %d times!", counter);
return 0;
}
I do not see any "counter" variable initialization
int counter = 1;
I do not see the new random number regeneration in the cycle, it should be something like:
do {
printf("is it %d? ", num_between_x_and_y);
scanf("%s", input);
if (input[0] == 'L') {
counter++;
maxNumber = num_between_x_and_y;
}
if (input[0] == 'H') {
counter++;
minNumber = num_between_x_and_y;
}
num_between_x_and_y = (rand() % (maxNumber - minNumber)) + minNumber;
} while (input[0] != 'G');
You can't use == to compare strings (which are multiple bytes).
Either do if (input[0] == 'L') to just compare the first letter the user entered to a literal value, or if (strcmp(input,"L") == 0) to compare everything the user entered to the 1 character string literal (to use strcmp you will need to add #include <string.h>
Also your code is missing other things, like counter should be set to presumably set to zero before you use it. I assume you haven't finished your code yet because you can't get the user input part to work.

Performing arithmetic on Characters in C

I am trying to write a program that adds, subtracts, multiplies, and divides a string of characters. Where I'm at now with the program is figuring out how to split the input string into two strings, and then perform the appropriate +-/*.
The input should look like this abc+aaa
and the output for that should be abc + aaa = bcd
How do I convert character strings into integer strings?
#include <stdio.h>
#include <math.h>
#include <string.h>
int main() {
printf("This is a pseudo arithmetic program");
char input[10];
input[10] = '\0';
char first [9];
first[9] = '\0';
char last [9];
last[9] = '\0';
int i = 0;
int b;
int e;
while (input[0] != '0') {
if (input[0] == 0){
return -1;
}
printf("\nEnter a math problem in SOS format using only lowercase letters up to 9 characters");
printf("\nEx: abc+abc... type '0' to quit \n");
scanf("%s", input);
int x = 0;
x = strlen(input);
if (strchr(input, '+')){
for (i = 0; i <= x; i++) {
if (i == '+')
strncpy(first, &input[0], i-1);
i = 0;
}
for (i = x; i >= input[0]; i--) {
if (i == '+')
strncpy(last, &input[i], x);
i = 0;
}
printf("%s", first);
printf(" + ");
printf("%s", last);
printf(" = %d", first + last);
}
There seems to be multiple problems with your code:
There is a array out of bounds happening for almost all the arrays:
char input[10];
input[10] = '\0';
In this if you want to initialize the last character with '\0' then it should be
input [9] = '\0'
Arrays indexes always start from 0.
It is not clear what is the use of below lines:
while (input[0] != '0') { if (input[0] == 0){ return -1; }
When taking input for a string, why are prompting users to enter a 0 to end it?
strrchr returns the pointer from where the searched character begins. So, you can that itself to determine where the '+' symbol is and two split the strings instead of your while loop. See strrchr man page
Also, your idea of adding characters is not clear. From your example, it appears you are considering a = 1, b = 2 etc. In such a case, if your code is case insensitive, then you can convert all your input to upper case and then do (input[0] - 'A')+1 to convert your letters like a, b, c to 1, 2, 3 etc.
Hope these pointers help. Suggest you check your problem statement again and refactor your code accordingly.

Resources