i have a question, my loop is stopping at sequence 2, i want to infinite loop the function ambil_nilai() and ulang() until scanf receiving the word "tidak" and then the program stop, and it seems i can't quite right to do it, please please help me, and please tell me if there's any not quite right in my ode, thank you very much for your help.
#include <stdio.h>
int ambil_nilai(){
int nilai, NMK;
printf("Masukkan mata kuliah yang ingin dicari analisa nya:\n");
scanf("%d",&NMK);
printf("Masukkan nilai mata kuliahnya:\n");
scanf("%d",&nilai);
if(nilai<=50){
printf("kamu harus belajar lagi karena nilai kamu kurang\n\n");
}
else if(nilai>=51){
printf("nilai kamu sudah cukup untuk lulus mata kuliah\n\n");
}
return 0;
}
char ulang(){
char lagi='y';
char tidak='n';
printf("ingin coba mata kuliah lain? tekan y untuk yes, n untuk no\n");
scanf("%c %c", &lagi,&tidak);
if(lagi){
system("clear");
return ambil_nilai();
}else if(tidak){
printf("terima kasih sudah menggunakan program ini\n");
}
return 1;
}
int main()
{
printf("\n\n");
printf("ini adalah mata kuliah kamu:\n");
printf("1. A\n");
printf("2. B\n");
printf("3. C\n\n");
ambil_nilai();
ulang();
printf("\n\n");
return 0;
}
I just want to correct matt93 code with an explanation :
First, you malloc a fixed size, so that's not really useful. Plus, you didn't check if malloc doesn't return NULL.
Moreover, your scanf is flawed, since we can easily do a buffer overflow.
In addition, you doesn't flush stdin, so when the loop continu, you will have a behavior in your program that you don't really want.
Here the code that correct all of this :
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define STR_HELPER(str) #str
#define STR(str) STR_HELPER(str)
#define ARRAY_LEN 5
int main(void)
{
char string[ARRAY_LEN + 1];
int c;
do {
printf("Enter 'tidak' please\n");
scanf("%"STR(ARRAY_LEN)"[^\n]", string);
while ((c = getchar()) != '\n' && c != EOF);
printf("Got : '%s'\n", string);
} while (strcmp(string, "tidak") != 0);
return (0);
}
You can read this for STR_HELPER and STR macro.
Don't forget to read scanf man if you have another question.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *string = (char*) malloc(60, sizeof(char));
while (scanf("%s", string) > 0) {
if (strcmp(string, "tidak") == 0) break;
}
let me know, if this was what you were looking for
Related
I have been working some time on the code below but for some reason there is no way I can print out correctly the chars array of an array after returning it and using it in the main function.
I cannot come up with any other things I could print in the code to check what is wrong. I do have checked other similar posts in the forum but I cannot spot any differences between the answers given there and how my code is written.
Does anyone spot anything wrong?
Many thanks in advance.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX_STRING 35
char **getWordsList(size_t *wordsNumber);
int main(){
int wordsNumber;
char **arrayOfArrays=getWordsList(&wordsNumber);
printf("WordsNumber is %d",wordsNumber);
printf("\nPrinting the resulting array of arrays: \n");
for (size_t indx=0; indx<wordsNumber; indx++){
printf("%s ", *(arrayOfArrays+indx)); //WHY ISNT THE STRING PRINTED CORRECTLY ?
}
free(*arrayOfArrays);
free(arrayOfArrays);
return 0;
}
char **getWordsList(size_t *wordsNumber){
printf("Please enter the number of words: ");
scanf("%zu",wordsNumber);
fflush(stdin);
char **wordsList=malloc(sizeof (char *)*(*wordsNumber));
if (wordsList!=NULL){
for (size_t indx=0; indx<*wordsNumber; indx++)
{
char inputWord [30];
printf("Please enter a word: ");
fgets(inputWord,sizeof(inputWord),stdin);
fflush(stdin);
printf("Word is %s",inputWord);
*(wordsList+indx)=malloc(MAX_STRING*sizeof(char));
if (*(wordsList+indx)){
*(wordsList+indx)=inputWord;
printf("Added array component is: %s\n",*(wordsList+indx));
}
}
return wordsList;}
else{
printf("Error in allocating memory for array of arrays");
}
}
Thanks to the help I got from the post comments, I was able to produce a working code. I am posting it so others who are struggling wih similar problems can benefit from it.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX_STRING 35
char **getWordsList(size_t *wordsNumber);
int main(){
int wordsNumber;
char **answer=getWordsList(&wordsNumber);
printf("WordsNumber is %d",wordsNumber);
printf("\nChecking: \n");
for (size_t indx=0; indx<wordsNumber; indx++){
printf("%s ", answer[indx]);
free(answer[indx]);
}
free(answer);
return 0;
}
char **getWordsList(size_t *wordsNumber){
long wordsNumberFoo;
char wordsNumberStr [40];
char *wordsNumberPtr;
printf("Please enter the number of words: ");
fgets(wordsNumberStr, sizeof(wordsNumberStr), stdin);
wordsNumberFoo=strtol(wordsNumberStr, &wordsNumberPtr, 10);
*wordsNumber=(size_t)wordsNumberFoo;
char **wordsList=malloc(sizeof (char *)*(*wordsNumber));
if (wordsList!=NULL){
for (size_t indx=0; indx<*wordsNumber; indx++)
{
char inputWord [30];
printf("Please enter a word: ");
fgets(inputWord,sizeof(inputWord),stdin);
inputWord[strcspn(inputWord, "\n")] = 0;
printf("Word is %s\n",inputWord);
strncpy(*(wordsList+indx),inputWord, MAX_STRING);
printf("Added array component is: %s\n",*(wordsList+indx));
}
return wordsList;}
else{
printf("Error in allocating memory");
return NULL;
}
}
This a reverse string code but the loop cant be terminated and keeps taking input
How can I terminate it
#include <stdio.h>
#include <string.h>
#define len 100
int main() {
char str[len];
int i;
do {
gets(str);
for (i = (strlen(str) - 1); i > -1; i--) {
printf("%c", str[i]);
}
printf("\n");
} while (str[0] != '\0');
return 0;
add str[0]='\0'; before gets and its done. this is because making a loop termination and to get out of the loop after clicking enter.
#include <stdio.h>
#include <string.h>
#define len 100
int main() {
char str[len];
int i,lenh;
do{
str[0]='\0';
gets(str);
lenh=strlen(str);
for(i=lenh-1;i>=0;i--)
{
printf("%c",str[i]);
}
printf("\n");
}while(str[0]!='\0');
return 0;
}
now, there are a few points (answer code below)
Basically, you are printing hand-to-hand with input, while the question states of a multi line input. So, first you have to take all the inputs and then output will be shown.
Your original code does not keep taking input as you have said. Question says the last string is empty string. You press enter in empty string, your above code will terminate.
Remember Last Input String Should be Empty, that's termination condition
#include <stdio.h>
#include <string.h>
int main(){
char str[100];
char stringArray[50][100]={0};
int k,m,count=0,i=0,j=0;
do {
fgets(str,100,stdin);
k=strlen(str);
for(m=0;m<k-1;m++){
stringArray[count][k-m-2]=str[m];
}
count++;
}
while (str[0] != '\n');
for(i=0; i<count; i++){
for(j=0;stringArray[i][j]!=0;j++){
printf("%c",stringArray[i][j]);
}
if(i<count-1){
printf("\n");}
}
return 0;
}
sample input
Hello team Loop
Welcome
sample output
pooL maet olleH
emocleW
How do I put isalpha and isdigit in a while(1) loop?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int main()
{
int i;
char type[256];
printf("You can type a number or a word. Type exit to exit! \n");
printf("Type: ");
fgets (type, 256, stdin);
if (isalpha(type[i]))
{
printf("Typed text: %s\n", type);
if((strcmp(type,"exit\n") == 0))
{
printf("Exiting...\n");
exit(1);
}
}
else if (isdigit(type[i]))
{
printf("Typed number: %s\n", type);
}
else
{
printf("Typed: %s\n", type);
printf("Its not a letter or number...?!\n");
}
}
I tried adding while(1) at the start at the code and close it at the end of code, but as soon as I enter number or letter the console crashes... Could someone please help me with this?
Your problem is not a loop problem, you need to give a value to i , as it is undefined and you get a nice crash. Please replace
int i;
with
int i=0;
I kind of have a basic question for you because it's driving me crazy. How do I go about writing my functions to specific strings? Like, if I was creating a while loop and wanted the program to end, how would I write it so that the program itself ends when I type in "end" when it asks for input?
EDIT: Alright, so I figured out pretty easily how to end my function by typing "end", but now for some reason depending on how many sentences I write, my program keeps repeating itself.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void){
int i;
char buf[10];
printf("Command? ");
scanf("%s", buf);
while(buf != "end")
{
if(strcmp(buf, "end")== 0){
break;
}
switch( buf[i] ){
//Where the cases will inevitably go
default:
puts("I'm sorry, but that's not a command.\n");
break;
}
printf("Command? ");
scanf("%s", buf);
}
puts("End of Program.");
getch();
}
char *myInputString = NULL;
while (1) {
/* read in myInputString from user input, and test... */
if (strcmp(myInputString, "foo") == 0)
break;
}
return EXIT_SUCCESS;
input value 123 -- this value is integer, and valid
input value 1b23a -- this value is invalid
How do I detect which values are valid and not?
Here is my code:
#include <stdio.h>
#include <conio.h>
void main()
{
char str1[5],str2[5];
int num,num1,i;
num=0;
clrscr();
printf("Enter the Number ");
scanf("%s",str1);
for(i=0;str1[i]!='\0';i++)
{
if(str1[i]>=48&&str1[i]<=56)
num=num1*10+(str[i]-48);
else
{
printf("The value is invalid ");
}
}
printf("This Number is %d",num);
getch();
}
Please see this answer regarding use of strtol(). It is a safe way to convert arbitrary input that should be a string representation of an integer, while also saving 'garbage' bytes for additional analysis.
Using it, your code would look something like this:
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#ifdef LINUX_VERSION
#include <curses.h>
#else
#include <conio.h>
#endif
#define BUFF_SIZE 1024
int main(void)
{
char str1[BUFF_SIZE], *garbage = NULL;
long num = 0;
printf("Enter the Number ");
scanf("%s",str1);
errno = 0;
num = strtol(str1, &garbage, 0);
if (errno) {
printf("The number is invalid\n");
return 1;
}
printf("You entered the number %ld\n", num);
if (garbage != NULL) {
printf("Additional garbage that was ignored is '%s'\n", garbage);
}
getch();
return 0;
}
This doesn't fix everything that is questionable about what you posted, but it should help you get off to a better start.
Output is:
tpost#tpost-desktop:~$ ./t
Enter the Number 1234abdc
You entered the number 1234
Additional garbage that was ignored is 'abdc'
Compiled via:
gcc -Wall -DLINUX_VERSION -o t t.c -lcurses
I'm not sure what platform you are using, so additional fixes to the code may be needed.
#include<stdio.h>
#include<conio.h>
void main()
{
char str1[5],str2[5];
int num,num1,i;
num=0;
clrscr();
printf("Enter the Number ");
scanf("%s",str1);
for(i=0;str1[i]!='\0';i++)
if(str1[i]>=48&&str1[i]<=56)
num=num1*10+(str[i]-48);
else
{
printf("The value is invalid ");
}
}
printf("This Number is %d",num);
getch();
}
One way is to use sscanf and check that there are no characters following the number. This is done most easily by adding a %c on the end and testing the return code, like this:
const char *yourString = ...;
int theValue, dummy;
if (sscanf(yourString, "%d%c", &theValue, &dummy) == 1) {
// Was a pure number, parsed into 'theValue'
} else {
// Either no number or had junk after it
}