How could I write this without using an integer? - c

#include <stdio.h>
#include <string.h>
int main(void)
{
char alpha[26] = { '0' };
char nl;
while (alpha != '0'){
scanf("%c", &alpha);
scanf("%c", &nl);
printf("the character is %c\n", alpha);
}
int i, j, size;
for (i=0;i<size;i++){
for (j=i;j<size;j++){
if (alpha[i]<alpha[j]){
Swap(&alpha[i], &alpha[j]);
}
}
}
printf("%s", alpha);
return 0;
}
I'm getting an error "comparison between pointer and integer" in my while loop. I'm wanting to read in each letter of the alphabet from a text file and stop when it reaches a "0" at the end of the list. It's then going to sort alphabetically starting with z,y,x.. etc. How else could I write this so it stops at "0" without using an integer?
Thanks for the help

alpha [26] is an array of 26 chars, with your while loop you always overwrite the first element of the array (scanf("%c", &alpha); overwrites the first element of alpha in every iteration of the loop ) , the entire code will not work. to access the elements of the array you can either use pointers or indexes, indexes are easier, try a for loop
int i;
for (i = 0; i<26 ; i++)
{
if(alpha[i] != '0')
{
scanf("%c", &alpha[i]);
printf("the character is %c\n", alpha[i]);
}
}
C: scanf to array
for using pointers to access array see Can i use pointer in scanf to take input in an array?

Related

I mixed up two programs in the cs50 sandbox in c?

I mixed up two programs in the cs50 sandbox, one was to find the the number of characters in an array and other was the print these characters. I know the program is garbage but could anyone explain me what is the compiler doing here?
When I ran this, the output starts printing alphanumeric text and never stops Thanks
#include <cs50.h>
#include <stdio.h>
#include <string.h>
int main(void)
{
string s = get_string("Name: ");
int n = 0;
while (strlen(s) != '\0')
{
n++;
printf("%c", n);
}
}
You have multiple problems with the code you show, here's a couple of them:
strlen(s) will never be zero as you never modify or remove characters from the string, which means you have an infinite loop
n is an integer and not a character so should be printed with the %d format specifier
'\0' is (semantically) a character, representing the string terminator, it's not (semantically) the value 0
To fix the first problem I suspect you want to iterate over every character in the string? Then that could be done with e.g.
for (int i = 0; i < strlen(s); ++i)
{
printf("Current character is '%c'\n", s[i]);
}
But if all you want is to could the number of characters in the string, then that's what strlen is already gives you:
printf("The number of characters in the string is %zu\n", strlen(s));
If you want to count the length of the string without using strlen then you need to modify the loop to loop until you hit the terminator:
for (n = 0; s[n] != '\0'; ++n)
{
// Empty
}
// Here the value of n is the number of characters in the string s
All of this should be easy to figure out by reading any decent beginners book.
while (strlen(s) != '\0') is wrong. '\0' equals 0. There string length is never 0, so the loop keeps going on forever, printing integers interpreted as characters.
You can either use the indexes to go through the string characters by using the variable "n" or you can increment the pointer of the string that you have received from the standard input to go through all of its characters.
#include <cs50.h>
#include <stdio.h>
#include <string.h>
int main(void)
{
string s = get_string("Name: ");
/* First way using n to iterate */
int n = 0;
for (n = 0; n < strlen(s); ++n)
{
printf("%c", s[n]);
}
printf("\n");
/* Second way increment the string pointer*/
while (strlen(s) != '\0')
{
printf("%c", *s); //print the value of s
s++; // go to the next character from s
}
printf("\n");
return 0;
}

Adding values from a file to an array until a certain character

I am working on a program that uses file redirection to read in a file, read one character per line until I reach a '0', store the characters in an array , and sort that array (from largest to smallest). Anyway, I really only need help with reading the characters until the zero shows up. Below is the text file that I am reading in:
f
k
s
j
p
a
v
r
t
u
h
m
g
e
b
y
n
z
w
l
i
x
q
c
o
d
0
Below is the code I have so far:
int main(void)
{
int i=0;
char array[100];
while(fscanf(stdin, "%c", &array[i]) && array[i]!='0')
{
i++;
}
int N = (sizeof(array)/sizeof(array[0]));
for(i=0;i<N;i++)
{
printf("%c", array[i]);
}
return(0);
}
When I run this program, it prints out every line of the file, including the zero. It also prints out some really weird characters after the zero (using gcc compiler). What am I doing wrong?
You need to set N to the value of i, currently it will always be 100
You use i to keep track of how many items you've read, but then you overwrite the value of i in your loop and print out all 100 elements, whether you stored something there or not.
Use different variable for counting the element than you do for looping, and use the count as your loop limit.
int count=0;
char array[100];
while(fscanf(stdin, "%c", &array[count]) && array[count]!='0')
{
count++;
}
for(i=0;i<count;i++)
{
printf("%c", array[i]);
}
fscanf needs to skip the separator (enter or space), else it will be incorporated into your list. Adding a space fixes that.
#include <stdio.h>
#include <stdlib.h>
int sort (const void *a,const void *b)
{
return ((int)*((unsigned char *)a)) - ((int)*((unsigned char *)b));
}
int main (void)
{
unsigned char array[100],i=0;
while (fscanf(stdin," %c", &array[i]) && array[i] != '0')
i++;
qsort (array,i,1,sort);
while (i)
printf ("%c\n", array[--i]);
}
It may seem this program sorts the wrong way around but the printing loop also happens to print in reverse, so that solves it neatly. As the array is unsigned char, the sort routine casts this to int to prevent possible overflow.

Using scanf for character input, but the do-while loop wont stop at the null character

I'm completely new to programming (1st term in uni) and I can't keep up with my lecturer. At the moment I'm stuck on this exercise (for much more time than I'm willing to admit). I've tried to find help on the internet (in this site and others as well), but I can't, since our lecturer has us use a very simple form of c. I'm not asking necessarily for a complete answer. I'd really appreaciate even some hints about where I'm on the wrong. I understand that it might be really simple for some, that the question might seem ignorant or stupid and I feel bad for not getting what's wrong, but I need to try to understand.
So, what I'm trying to do is use scanf and a do while loop so the user can input characters in an array. But I don't understand why the loop won't stop when the user presses ENTER. There's more to the code, but I'm trying to take it slowly, step by step. (I'm not allowed to use pointers and getchar etc).
#include <stdio.h>
main()
{
char a[50];
int i;
printf("Give max 50 characters\n");
i=0;
do
{
scanf("%c", &a[i]);
i=i+1;
}
while((i<=50) && (a[i-1]!='\0'));
for(i=0; i<50; i++)
printf("%c", a[i]);
}
There aren't any nul-terminated strings here, but only string arrays.
So, when pressing enter, a[i-1] is \n not \0 (scanf with %c as parameter doesn't nul-terminate the strings, and ENTER is just a non-nul character with code 10 AKA \n)
Then don't print the rest of the string because you'll get junk, just reuse i when printing the string back:
#include <stdio.h>
main()
{
char a[50];
int i;
printf("Give max 50 characters\n");
i=0;
do
{
scanf("%c", &a[i]);
i=i+1;
}
while((i<sizeof(a)) && (a[i-1]!='\n')); // \n not \0
int j;
for(j=0; j<i; j++) // stop at i
printf("%c", a[j]); // output is flushed when \n is printed
}
Also test with i<50 not i<=50 because a[50] is outside the array bounds (I've generalized to sizeof(a))
Here is another way you can do this.
#include <stdio.h>
// define Start
#define ARRAY_SIZE 50
// define End
// Function Prototypes Start
void array_reader(char array[]);
void array_printer(char array[]);
// Function Prototypes End
int main(void) {
char user_input[ARRAY_SIZE];
printf("Please enter some characters (50 max)!\n");
array_reader(user_input);
printf("Here is what you said:\n");
array_printer(user_input);
return 0;
}
// Scans in characters into an array. Stops scanning if
// 50 characters have been scanned in or if it reads a
// new line.
void array_reader(char array[]) {
scanf("%c", &array[0]);
int i = 0;
while (
(array[i] != '\n') &&
(i < ARRAY_SIZE)
) {
i++;
scanf("%c", &array[i]);
}
array[i + 1] = '\0';
}
// Prints out an array of characters until it reaches
// the null terminator
void array_printer(char array[]) {
int i = 0;
while (array[i] != '\0') {
printf("%c", array[i]);
i++;
}
}
You may try with this code:
#include <stdio.h>
main()
{
char a[50];
int i;
printf("Give max 50 characters\n");
i=0;
do {
scanf("%c", &a[i]);
i=i+1;
} while(i<50 && a[i-1] != '\n');
a[i] = 0;
for(i=0; a[i] != 0; i++)
printf("%c", a[i]);
}
The function scanf("%c", pointer) will read one character at a time and place it at the pointer location. You are looking for '\0', which is a valid string terminator, but the newline character you get when you press ENTER and that you should be looking for is '\n'.
Also, it is a good idea to terminate the string you have read by adding a '\0' at the end (really a zero). Then use it to stop printing or you may print the "rest" of the contents of an uninitialized char array.

What is wrong in my C code for a program about strcmp()?

I am writing a program for comparing two strings without using strcmp(). But, am unable to get my desired result.
Here is the code for my program.
#include<stdio.h>
int main(int argc, char const *argv[]) {
int i,j;
char a[90],b[90];
printf("Enter the first string:");
scanf("%s", &a[90]);
printf("Enter the second string:");
scanf("%s", &b[90]);
for ( i = 0; a[i] != '\0' && b[i] != '\0'; i++) {
if (a[i] == b[i]) {
/* code */
printf("Equal %d \n", a[i]-b[i]);
continue;
} if (a[i] > b[i]) {
/* code */
printf("ai is big %d \n", a[i]-b[i]);
break;
}
if (a[i] < b[i]) {
/* code */
printf("%d bi is the biggest \n", a[i]-b[i]);
break;
}
}
return 0;
}
When I execute the program in my terminal the compiler takes the input strings and then stops. I tried it a lot but am unable to figure it out. Can anyone help me out...!
The name of your first array is a, not a[90].
Similarly, the name of your second array is b, not b[90].
The expressions a[90] and b[90] name one element after the end of a and b.
So, by writing &a[90] and &b[90] you are instructing scanf to write just after each array, which is very bad and wrong.
You probably meant &a[0] and &b[0]?
However, scanf is very dangerous and you should not be using it at all.
The expressions '&a[90]' and '&b[90]' each generate the addresses of the last entries in arrays a and b. That means you are reading the strings into unallocated stack memory, not into the arrays. You need to just use plain 'a' and 'b' in the scanf() calls.
If you are now wondering "How does scanf know to limit the strings to 90 characters?", the answer is IT NEVER DOES. Scanf assumes the caller has provided enough buffer space for the entered string (including terminating null-char). If you really need to be able to enter arbitrarily long strings, you will have to perform much more sophisticated buffer management. If you only want to ensure less than 90 characters are ever entered, you need to drop down to getting one character at a time (and I believe you will have to explicitly check for the terminating newline) and count them to ensure you don't overflow the buffer.
There is some issue with the given code in question.
issues
1- Unused variable j.
2- While getting the string from user, in scanf a[90] and b[90] is used that means string will be stored from 90th array index. This can lead to some memory issues and output will have some garbage values.
Its is good to use a[0] and b[0] in scanf. We can use array name in scanf as array name points to the starting address of array.
scanf ("%s", a);
scanf ("%s", b);
Correct code :
#include "stdio.h"
int main(int argc, char const *argv[])
{
int i;
char a[90],b[90];
printf("Enter the first string:");
scanf("%s", a);
printf("Enter the second string:");
scanf("%s", b);
for ( i = 0; a[i] != '\0' || b[i] != '\0'; i++) {
if (a[i] == b[i]) {
/* code */
printf("Equal %d \n", a[i]-b[i]);
continue;
} if (a[i] > b[i]) {
/* code */
printf("a is big %d \n", a[i]-b[i]);
break;
}
if (a[i] < b[i]) {
/* code */
printf("%d b is the biggest \n", a[i]-b[i]);
break;
}
}
return 0;
}

C programming - Inverting a string

In this program i'm trying to invert a string using 2 arrays:
The problem here is the program keeps writing the character "P" as the only output and i can't seem to figure out how to solve this.
#include<stdio.h>
#include<string.h>
#define TAM 256
int get_string(char string[TAM]);
int invert_string(char string[TAM]);
int string_out(char string[TAM]);
int main(){
char string[TAM]={0}; // always initialize a string to be completely zero, or unexpected behaviour may occur
get_string(string);
invert_string(string);
return 0;
}
int get_string(char string[TAM]){
printf("Enter a string: ");
scanf("%s",string);
return 0;
}
int invert_string(char string[TAM]){
char temporary_string[TAM]={0};
int i,j;
for(i=TAM,j=0;i>=0;i--){
if(string[i]== ' '){
continue;
}else{
temporary_string[j] = string[i];
j++;
}
}
printf("debug : temp string is : %s",temporary_string);
return 0;
}
int string_out(char string[TAM]){
printf("%s",string);
return 0;
}
Try this code in invert_string function:
int i,j;
for(i=strlen(string)-1,j=0;i>=0;i--){ // u can take variable and save length or directly pass length
if(string[i]== ' '){
continue;
}else{
temporary_string[j++] = string[i];
}
}
temporary_string[j] = '\0'; //Make last index NULL
printf("%s",temporary_string);
For an array declaration / definition of arr[256], the last element is arr[255].
In your for() loop,
for(i=TAM,j=0;i>=0;i--)
you're accessing arr[256] [267th element, considering index starts from 0] which is out-of-bound access and hence produces undefined behavior.
Then, the terminating NULL in the source array should be taken care of separately.
You need to have something like
if((string[i]== ' ') || (string[i]== '\0')){//....
Otherwise, the terminating NULL will become the first vaild element in the destination array, thus will end up printing nothing.
Lastly, don't forget to NULL terminate the new array.
temporary_string[j] = '\0';
Note: Once you'vre fixed this version of code, think of some optimization.
Check the below code.
#include<stdio.h>
#include<string.h>
#define TAM 256
int get_string(char string[TAM]);
int invert_string(char string[TAM]);
int string_out(char string[TAM]);
int main(){
char string[TAM]={0}; // always initialize a string to be completely zero, or unexpected behaviour may occur
get_string(string);
invert_string(string);
return 0;
}
int get_string(char string[TAM]){
printf("Enter a string: ");
scanf("%s",string);
return 0;
}
int invert_string(char string[TAM]){
char temporary_string[TAM]={0};
int i,j;
for(i=TAM-1,j=0;i>=0;i--){
if((string[i]== ' ') || (string[i]== '\0')){
continue;
}else{
temporary_string[j] = string[i];
j++;
}
}
temporary_string[j] = '\0';
printf("debug : temp string is : %s\n",temporary_string);
return 0;
}
Make you loop condition starting with 255.
for ( i=TAM-1 ; j=0; i>=0 ; i--)
...
256 is array out of bounds.
There are lot of issues with your code. At first you cannot start with 256 as i mentioned in the comment. Again you don't know how much is the length of the source string. Even if u have taken the size to be 256 the string inputted from the terminal can be of length smaller than 256. So first you must know what is the size of the string inputted from the terminal. After that start with strlen(string) - 1 and copy until i becomes 0. Then do temporary_string[strlen(string)-1]='\0'

Resources