String to int array - c

I've worked on this for awhile but I keep getting either {0,0,0,0,0}, or {2751685, 2751685, etc} or {57,58,59,60,etc}
void getGuess(int guess[], int length) {
char thisGuess[length];
int i=0;
printf("Enter your guess.\n");
scanf("%s", &thisGuess);
for(i=0; i<length; i++) {
printf("the guess = %d\n",(int)thisGuess[i]) ;
guess[i] = (int)(thisGuess)-48;
printf("%d ", guess[i]);
}
}
I want to enter a string, 12345, and get it so
guess[0] = 1
guess[1] = 2
guess[2] = 3
etc
suggestions on my code?

The length of an char array usually isn't equal to the length of the C-style string it contains.
void getGuess(int guess[], int length) {
char thisGuess[length];
size_t i = 0;
printf("Enter your guess.\n");
scanf("%s", thisGuess); // a char *, rather than a char (*)[length] is expected
size_t guessLength = strlen(thisGuess);
for(i = 0; i < guessLength; i++) {
printf("the guess = %d\n", thisGuess[i]);
guess[i] = thisGuess - '0';
printf("%d ", guess[i]);
}
}
Alternatively, add
if(!isdigit(thisGuess[i]))
continue;
to avoid potential out-of-bound access.

Related

Need some help how to enter a number and count it using array

I have to code in an array that can count an element. For example, if the user enters a 2, 2, 2, 1,1 then the user wants to count the number 2 then the result will be ELEMENT is 2 and FREQUENCY is 3. but I have a problem with the parts of " ENTER THE NUMBER YOU WANT TO BE COUNTED". I use scanf but when I run it I cannot enter any number.
Here's my code:
void frequency()
{
system("cls");
int num;
int count=0;
printf("Enter a number you want to be count: \n ");
scanf("i%", &num);
printf(" ELEMENT | FREQUENCY \n ");
for (i = 0; i<=n; i++)
{
if (a[i]==a[num])
count++;
}
printf(" \n %i ", num);
printf(" \t\t");
printf("%i \n ", count);
getch();
}
Your program requires understanding on two parts:
Get input and split input by delimiter, which can be done by using strtok.
Algorithm for finding the duplicated elements in an array.
#include <stdio.h>
#include <string.h>
int main() {
frequency();
return 0;
}
void frequency() {
char str[100];
printf("Enter a number you want to be count: \n ");
gets(str);
int init_size = strlen(str);
char delim[] = " ";
char *ptr = strtok(str, delim);
char *pch;
int arr[20];
int count = 0;
int ncount, i, j;
int a[count], Freq[count];
while(ptr != NULL) {
/*printf("'%s'\n", ptr);*/
/*Converts the string argument str to an integer (type int)*/
arr[count] = atoi(ptr);
/*strtok accepts two strings - the first one is the string to split, the second one is a string containing all delimiters*/
ptr = strtok(NULL, delim);
/*Initialize frequency value to -1*/
Freq[count] = -1;
count += 1;
}
/*Count the frequency of each element*/
for (i = 0; i < count; i++) {
ncount = 1;
for(j = i + 1; j < count; j++) {
/*Part to perform checking for duplicate elements*/
if(arr[i] == arr[j]) {
ncount++;
/*Make sure not to count frequency of same element again*/
Freq[j] = 0;
}
}
/*If frequency of current element is not counted*/
if(Freq[i] != 0) {
Freq[i] = ncount;
}
}
printf(" ELEMENT | FREQUENCY \n");
printf("-------------------------\n");
for (i = 0; i < count; i++) {
if(Freq[i] != 0) {
printf("\t%d\t\t\t%d\n", arr[i], Freq[i]);
}
}
}
Also, from your code:
You did not define i and n, which is required by your for loop. Also, since your for loop is for (i = 0; i<=n; i++), you have to define the value of n, which is the length of elements inputted by the user, in order to loop through the number of elements you expected.
int i, n, num;
...
...
for (i = 0; i<=num; i++)
Your scanf("i%", &num); should be scanf("%i", &num); instead.
You did not initialize your array a. You should have this line of code before assigning values to your array a. The value 20 can be adjusted by yourself depending on how many inputs are expected. Also, it can be coded in a flexible way instead of hardcoded as 20.
...
int i, num;
int count=0;
int a[20];
...
...
Lastly, it is a good practice to include the function's library before using it. In your case, you should include #include <conio.h> to use the getch() function.

rearranging a char array with strncpy in C

I am trying to change the sorting of a the arr list which could consist of zero, one, two as the inputted and stored values for arr. The stringreplace function is meant to shift every single element by one so the new sorting would be one, two, zero. I am trying to replace the elements with one another by using the strncpy function but I think it is a bit faulty, how could i fix this?
strncpy function
char stringreplace( char a[], int b){
for(int j = 0; j > b -1; j++){
strncpy(a[j], a[j+1], sizeof(a));}
for(int j = 0; j > b; j++){
printf("%s",a[j]);}
}
main function
int main()
{
char input[100];
char arr[100]= {0};
int number;
printf("Input the number of strings: ");
scanf("%d", &number);
for(int i= 0; i < number; i++){
printf("Input the number of strings: ");
scanf("%s", input);
arr[i] = input;
}
stringreplace(arr, number);
return 0;
}
You may consider allocating strings dynamically, assigning a pointer for each string into an array words, and then rotating each pointer in the array to the left.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void lrot_words(char *words[], int n);
int main(void)
{
char *p, word[100], *words[100];
int i, num_words;
printf("Enter the number of words: ");
scanf("%d", &num_words);
for(i = 0; i < num_words; i++){
printf("Enter a word: ");
scanf("%s", word);
if ((p = malloc(strlen(word) + 1)) == NULL) {
fprintf(stderr, "Error: malloc failed\n");
exit(EXIT_FAILURE);
}
words[i] = strcpy(p, word);
}
lrot_words(words, num_words);
for (i = 0; i < num_words; i++) {
printf("%s\n", words[i]);
}
return 0;
}
void lrot_words(char *words[], int n)
{
char *temp = words[0];
int i;
for (i = 0; i < n - 1; i++) {
words[i] = words[i+1];
}
words[i] = temp;
}

Arranging a character array using bubble sort

Here is my code so far. I am perfectly able to sort files holding numbers but clueless when it comes to characters. It takes in a file of my choosing and outputs another file with the sorted array. But so far all I'm getting are blank files and I can't figure out why.
So how can I fix my code to sort an array of characters and then output it?
#include <stdio.h>
int bubble_sort(char *a, int n);
int main(void) {
char a[10];
int n = sizeof a / sizeof a[10];
int i;
char inname;
char outname;
printf("Enter input name: ");
scanf("%s", &inname);
printf("Enter output name: ");
scanf("%s", &outname);
FILE *in, *out;
out = fopen(&outname, "w");
if ((in = fopen(&inname, "r")) == NULL) {
printf("File not found\n");
}
else {
for (int i = 0; i < 10; i++)
{
fscanf(in, "%s ", &a[i]);
}
bubble_sort(a, n);
for (i = 0; i < 10; i++) {
printf("%s\n", a[i]);
fprintf(out, "%s\n", a[i]);
}
}
fclose(in);
fclose(out);
return 0;
}
int bubble_sort(char *a, int n) {
int i, j;
char temp;
for (j = 1; j<n; j++)
{
for (i = 0; i<n - j; i++)
{
if ((int)a[i] >= (int)a[i + 1])
{
temp = a[i];
a[i] = a[i + 1];
a[i + 1] = temp;
}
}
}
return a[i];
}
The basic problem, as I can see, is with
scanf("%s", &inname);
In your code, inname is a single char, which cannot hold string inputs. You'll be needing an array.
You need to change
char inname;
char outname;
to
#define NAMSIZ 32
char inname[NAMSIZ] = {0};
char outname[NAMSIZ] = {0};
and then,
scanf("%31s", inname);
and accordingly.
Same problem exist with fscanf(in, "%s ", &a[i]);, too.

making a word search puzzle?

I've made a program that allows you to choose the size of the grid and it allows you to enter up to 20 words. Now I have to insert the entered words horizontally into the original array using a function. The function must return a value for success and a value for failure to enter the word into the puzzle board. I need help getting started with what the actual function should look like along with the function prototype. Pseudocode would be helpful. I'm a fairly new programmer so any help is great. Thank you
#include<stdio.h>
#include<string.h>
void printmatrix(char matrix[][20],int);
void inserthor(char matrix[][20],int);
int main(void)
{
//declare variables
char matrix[20][20];
char words[20][100];
int x;
int a,b;
int i=0;
int n=0;
for (a=0;a<20;a++)
{
for (b=0;b<20;b++)
{
matrix[a][b] = '+';
}
}
while (x<10 || x>20)
{
printf("How large would you like the puzzle to be (between 10 and 20):\n");
scanf("%d",&x);
}
printmatrix(matrix,x);
//part 3
printf("Enter up to 20 words to hide in the puzzle.\n");
printf("Enter the word 'done' after your last word if entering less than 20 words.\n");
for (i = 0; i < 20; i++)
{
printf("Enter word %2d:\n", i+1);
if (scanf("%99s", words[i]) != 1 || strcmp(words[i], "done") == 0)
break;
}
n = i;
printf("%d words entered\n", n);
for (i = 0; i < n; i++)
printf("Word %2d = [%s]\n", i+1, words[i]);
return 0;
}
void printmatrix(char matrix[][20],int x)
{
int i,j;
printf("Empty Puzzle:\n");
for (i=0;i<x;i++)
{
for (j=0;j<x;j++)
{
printf(" %c ", matrix[i][j]);
}
printf("\n");
}
}
Your function prototype
void inserthor(char matrix[][20],int);
lacks the parameter with the word to be entered and the value to be returned. You could use
char *inserthor(char matrix[][20], int order, char *word)
{
int i, j, l = strlen(word);
for (i = 0; i < order; ++i)
for (j = 0; j <= order-l; ++j)
if (matrix[i][j] == '+') return memcpy(&matrix[i][j], word, l);
return NULL;
}
which returns the address of the inserted word for success and NULL for failure.

Bubble sort in C. Output is the same as input

As a school assignment we are writing a bubble sort program in c. The code I wrote works. The only thing is that the output returns the input and doesn't return the swapped input. I'm kinda stuck. No matter what I do i either get an error or nothing changes. Does anybody know what is going wrong? Any help would be highly appreciated!!
#include <stdio.h>
#include <string.h>
#define MAXLENGTH 100
void getString(char *str);
void printResult(char *str);
int greaterThan(char ch1, char ch2);
void swap(char *str, int index1, int index2);
int main(void) {
int len; // length of the entered string
char str[MAXLENGTH]; // input should be no longer than MAXLENGTH
getString(str);
len = strlen(str); // get length of the string, from sting.h
int j;
for (j = 0; j < len-j; j++) {
int i;
for (i = 0; i < len-j; i++){
char ch1 = str[i];
char ch2 = str[i+1];
if (greaterThan(ch1, ch2)) {
swap(str, i, i+1); // swap char 1
swap(str, i, i+1); // swap char 2
}
}
}
printResult(str);
return(0);
}
void getString(char *str) {
printf("Enter the string you would like to sort: ");
scanf("%s",str);
}
void printResult(char *str){
printf("Here is the sorted string: ");
printf("%s",str);
}
int greaterThan(char ch1, char ch2){
return (ch1 > ch2);
}
void swap(char *str, int index1, int index2){
char h = str[index1];
str[index1] = str[index2];
str[index2] = h;
}
Try this:
getString(str);
len = strlen(str); // get length of the string, from sting.h
int j;
for (j = 0; j < len-j; j++) {
int i;
for (i = 0; i < len-j; i++){
char ch1 = str[i];
char ch2 = str[i+1];
if (greaterThan(ch1, ch2)) {
swap(str, i, i+1); // swap char 1
}
}
}
printResult(str);
return(0);
}
Here:
if (greaterThan(ch1, ch2)) {
swap(str, i, i+1); // swap char 1
swap(str, i, i+1); // swap char 2
}
you are swapping twice while you should swap only once.
I was bad the below part of my answer's previous version is not bubble short:
Another problem is that you are using elements next to each other and you are not using i and j indexed ones to compare and swap. So you better should have something like this:
if (greaterThan(str[i], str[j]))
swap(str, i, j);
if (greaterThan(ch1, ch2)) {
swap(str, i, i+1); // swap char 1
swap(str, i, i+1); // swap char 2
}
In this code you are swamping twice.
For Example: str = ['a','b','c'] swap(str,1,2) for first swap the " str " will be ['a','c','b'] and for the second swap " str " will be ['a','b','c']. That's why your Output is the same as input.
You Just Need To Call swap function only once.
if (greaterThan(ch1, ch2)) {
swap(str, i, i+1);
}

Resources