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.
Related
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.
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 6 years ago.
Improve this question
I need to convert a floating point csv to a 2D array in c. Have already saw an article (Import CSV elements into a 2D array in C) which explains the conversion to an integer array.Can any one help in modifying this code or a new approach that i could use to convert the csv to a floating point 2D array
for eg: my csv contains values like 0.018869,0.015863,0.044758,0.027318,0.049394,0.040823,..... and is a 4400*500 values csv. so i would need to use a big array of size 4400*500 to include all of these values.
Thanks in advance
Use atof() to convert strings to floats.
Here is a link if you want to read up on it
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//counters
int i = 0;
int j = 0;
int k = 0;
char c = 0; //for storing a char at a time
char result_char_array[4] = {0}; //float is a 32 bit number, so 4 bytes
FILE *filep; //pointer to file structure
float results[100] = {0}; //to store the float
int main(void)
{
filep = fopen("C:/Documents/test.csv", "r"); //open file , read only
if (!filep)
{
fprintf (stderr, "failed to open file for reading\n");
return -1; //return negative number so you know something went wrong
}
c = fgetc(filep); //get first character
while(c != EOF)
{
if((c == ',') || (c == '\n')) //we want to stop at each comma or newline
{
//i = 0; //reset the count
results[j] = atof(result_char_array); //this converts a string to a float
j++; //increment j
memset(&result_char_array, 0, sizeof(result_char_array)); //clear the array
}
else
{
strncat(&result_char_array, &c, 1);
}
c = fgetc(filep); //get next character
i++;
}
results[j] = atof(result_char_array); //convert last number
fclose (filep); //always close the file
for(k = 0; k <= j; k++)
{
printf("Number %d is: %f\n",k, results[k]); //loop through the results and print line by line
}
getchar();
return 1;
}
Take a look at libcsv, which is a CSV library written in ANSI C89. But be careful, libcsv is licensed under LGPL.
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.
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 8 years ago.
Improve this question
I'm very new to C and have the following issue. This program is supposed to read in exam scores from a data file and store the output into a text file. The output is supposed to be the number of grades as well as the number of each letter grade.
Whenever I run it, it crashes.
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *inFile;
int current;
int sum = 0;
int b;
int theGrades[100];
inFile = fopen("a.txt", "r");
b = fscanf(inFile, "%d", ¤t);
while(b != -1){
theGrades[sum] = current;
sum++;
b = fscanf(inFile, "%d", ¤t);
}
fclose(inFile);
for(int i=0;i<=sum;i++){
printf("%d" + theGrades[i]);
}
}
1) Check inFile (it must be valid pointer, not NULL)
2) Check sum counter (must be < 100)
3) printf("%d" + theGrades[i]); - what are you doing? Have you printf("%d", theGrades[i]); in mind?
Your for loop needs help
for(int i=0;i<sum;i++){ //not <=
printf("%d ", theGrades[i]); // comma, not a plus sign
}
Also, check fopen for failure. Ensure you don't add more than 100 items. Use EOF instead of -1.
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 9 years ago.
Improve this question
I'd like to ask you about my prog. The main purpose of this one is to fill the "result" array with data collect from "tab1" and "tab2" arrays. Could anybody check, why does results are so weird? Thank you.
#include <stdio.h>
#include <stdlib.h>
void laczenie(char tab1[],char tab2[])
{
int i;
char* result =(char*) malloc(100*sizeof(char));
for(i=0;i<30;i++)
{
if(tab1[i] != '\0') tab1[i]==result[i];
else if (tab2[i] !='\0')tab2[i]==result[i];
else printf(" ");
}
for(i=0;i<30;i++)printf("%c",result[i]);
free(result);
}
int main()
{
char x[10]={'n','a','p','i','s','1'};
char y[10]={'n','a','p','i','s','2'};
//char x[10] = {"napis1"};
//char y[10] = {"napis2"};
laczenie(x,y);
return 0;}
In addition to LihOs answer above this block looks wrong:
if(tab1[i] != '\0')
tab1[i]==result[i];
else if (tab2[i] !='\0')
tab2[i]==result[i];
else printf(" ");
Don't you mean to assign the value in tab1[i]or tab2[i] to result[i]like this?
if(tab1[i] != '\0')
result[i] = tab1[i];
else if (tab2[i] !='\0')
result[i] = tab2[i];
else printf(" ");
Also using magic numbers like in the loops: for(i=0;i<30;i++) is pretty bad practice, you should probably be using a constant for the size value (which you could then use in both the loops and in the array declarations. And why loop to 30 when the arrays is 10 elements only?
In your function you check for null-terminating character:
if(tab1[i] != '\0')
but where is null-terminating character here?
char x[10]={'n','a','p','i','s','1'};
Try:
char x[7]={'n','a','p','i','s','1','\0'};
Also note that tab1[i]==result[i]; compares tab[1] with result[i], if you want to assign the result[i] to tab1[i], use assignment operator =:
tab1[i]=result[i];
if(tab1[i] != '\0')
result[i] = tab1[i];
else if (tab2[i] !='\0')
result[i] = tab2[i];
else printf(" ");`
This is still wrong as by the time you assign tab2 to result i will be already at 6 so you will have to use two for loops i suppose for assign tab1 and tab 2