String Editor (not functioning correctly) - c

I'm new to C and have been set the following problem. I am to write a program where a string can be entered and stored, I should then enter two integer values which will then be used to remove characters from the string, afterwards the result should be printed. Once the program works it should be converted into a function.
I have created a program that will split the entered string into two strings which store the chars I want to keep in two buffers, afterwards the two strings are concatenated to give the resultant edited string. The problem I am having is that when I print the edited string I get random characters at the end and sometimes in between the two strings and I think it's because the strings are not being null terminated correctly. I hope that someone is able to help, Thanks :)
#include <stdio.h>
#include <string.h>
int main ()
{
char string [25];
char buffer1 [25];
char buffer2 [25];
int start;
int remove;
int i;
int finish;
int size;
int numbercopy;
int A, B, C;
printf("Enter a string: ");
gets(string);
printf("\nEnter a starting character position: ");
scanf("%d", &start);
printf("\nHow many characters would you like to remove? ");
scanf("%d", &remove);
finish = (start+remove);
size = strlen(string);
numbercopy = (size-finish);
strncpy(&buffer1[0], &string[0], start);
buffer1[start] = '\0';
strncpy(&buffer2[0], &string[finish], numbercopy);
buffer2[numbercopy] = '\0';
A = strlen(buffer1);
B = strlen(buffer2);
C = (A+B);
strcat(buffer1, buffer2);buffer1[C] = '\0';
for (i=0; i<25; i++)
{
printf("%c", buffer1[i]);
}
return 0;
}

Since it is a string, you do not need to print it character by character. Also, the loop indicates that only 25 char strings will be printed. If a string (buffer1) is shorter in length(<25), garbage values will be printed, if a string is is larger (>25), some chars will not be printed.
Change this:
for (i=0; i<25; i++)
{
printf("%c", buffer1[i]);
}
to this:
printf("%s", buffer1);

Related

Garbage characters are printed forcefully [duplicate]

This question already has answers here:
Why do we need to add a '\0' (null) at the end of a character array in C?
(9 answers)
Closed 4 years ago.
This is a program that's supposed to read inputs, a number 'n' and a character, and then duplicate this character n times. It works perfectly fine, but when I enter a large number, 8+ for example, it duplicates perfectly but then adds garbage values to the end. I can't get why it does that since I used malloc and I have exactly n blocks saved for me in the memory.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* create_string (char ch, int n);
void main ()
{
int n;
char ch;
printf("Enter number for duplicates: ");
scanf("%d",&n);
printf("Enter a letter: ");
scanf(" %c", &ch);
printf("The letter '%c' duplicated %d times is: ",ch,n);
char* ptr=create_string(ch,n);
printf("%s",ptr);
}
char* create_string (char ch, int n)
{
char* dup=(char*)malloc(n*sizeof(char));
int i;
for (i=0; i<n; i++)
{
dup[i]=ch;
}
return dup;
}
Test run:
Strings in C are as simple as null-terminated character sequences. That means whenever you create a string by hand, you must always append a '\0' at the end so other functions like printf know where it ends:
char* create_string (char ch, int n)
{
char* dup = malloc((n+1) * sizeof(char));
int i;
for (i=0; i<n; i++)
{
dup[i]=ch;
}
// This is important
dup[n] = '\0';
return dup;
}
Another subtle thing to notice is that because you need to store that terminating null character, you also need to reserve the space for it. So the malloc line is changed into:
malloc((n+1)*sizeof(char))
// ^^^^^ it's no longer 'n'
On a side note, you don't need to cast the returned pointer of malloc.
Strings in C are char arrays where the character \0 denotes the end of the string. Since you aren't explicitly adding it, printf just prints values from memory until it happens to run in to a terminating character (i.e., this is undefined-behavior). Instead, you should explicitly add this character to your result string:
char* create_string (char ch, int n)
{
char* dup = (char*) malloc((n + 1) * sizeof(char));
/* Added 1 for the '\0' char ---^ */
int i;
for (i = 0; i < n; i++)
{
dup[i]=ch;
}
/* Set the terminating char */
dup[n] = '\0';
return dup;
}

Want to store "char values" in array (in C language)

I want to store "char data type values" in an array, but it doesn't work.
First, I tried using "gets"
but it gave me a run time error.
Code was like this
int tmp = 0;
char arr[100] = { 0, };
while (arr[tmp]!=NULL)
{
gets(arr[tmp]);
tmp++;
}
for (int rtmp = 0; rtmp < a; rtmp++)
printf("%s ", arr[rtmp]);
return 0;
In a second way, I was using "scanf", but I couldn't store "char data type(it should be more than one character like string)", but only one character was available.(I tried %s, but it doesn't work)
Plus, it doesn't print the last value of array.
int a = 0;
scanf("%d", &a); //determine how much I input values
int tmp = 0;
char arr[100] ={ 0 , };
for(tmp=0;tmp<a;tmp++)
{
scanf("%c ",arr[tmp]);
fflush(stdin);
}
for (int rtmp = 0; rtmp < a; rtmp++)
printf("%c ", arr[rtmp]);
return 0;
The most "identical" for me is
without notifying "a" values("a" means how much values I input)
and storing "char values" in array..
How can I solve this problem?
Thanks in advance! Your help is always appreciated :)
Array of char data type is called Sting. You can take a string's input using scanf() and gets(). But if you use scanf(), the string will be input by pressing Space-bar or Enter. But if you use gets(), input will be given only by pressing the Enter key.
Example 1:
char s[100];
scanf("%s", s);
Example 2:
char s[100];
gets(s);
Now, if you want to input every single character individually, you can do that also:
char s[100], c;
int n, i, j;
scanf("%d", &n);
getchar();
for(i=0; i<n; i++) {
scanf("%c", &s[i]);
}
s[i] = '\0';
Now look, I wrote a getchar() after scanf("%d", &n);, because when you press enter after inputting n, a new line character ('\n') is also taken as input in the character next to n. So you must do this in case like this.
One more thing, you can take input any string containing spaces using scanf() also. Just do this:
char s[100];
scanf("%[^\n]", s);
You can not enter the individual character by following snippet of code.
char arr[10] = {0};
//unsigned char ch;
unsigned int i = 0;
printf("Enter the array elements\n");
for(i = 0; i<10; i++)
{
scanf("%c", &arr[i]);
printf("i = %d and arr[%d] = %c\n", i, i, arr[i]);
}
The result of this snippet is as per this image. enter image description here
To avoid this issue, it is recommended to enter the character without new line charactoer '\n' or without pressing enter.
Or other method is to use the array as string and input the character by gets() like this snippet.
char s[100];
gets(s);

Substring in C (what will happen to the remaining in array)

I have given a task to generate a sub string for the given input in C. The code as follows.
#include<stdio.h>
int main(){
char a[1000];
char *sub;
int startFrom = 0;
int endAt = 0;
printf("Enter the String: ");
scanf("%s", a);
printf("Start From? ");
scanf("%d", &startFrom);
printf("End At? ");
scanf("%d", &endAt);
sub = &a[startFrom];
a[endAt] = '\0';
printf("%s\n", sub);
return 0;
}
The code however works fine, but what will happen to the rest of the characters in the array?
The rest of the array remains the same; it's just that you changed one of the characters in the array to null('\0'). So if you try to access any other character after (or before) the a[endAt] character, you would be able to do so.
Check it out Your code with some extra at Ideone.com.
However as you can see, when you try to print the original array, it would be printed only till the first '\0' character.

C program Need help fixing my code for a word sort program

Hi I am still new to c and have been working on this word sort program for some time now. the guidelines are:
Write a program that sorts a series of words entered by the user. Assume that each word is no more than 20 characters long. Stop reading when the user enters an empty word. Store each word in a dynamically allocated string, using an array of pointers (use the read_line function). After all lines have been read sort the array. Then use a loop to print the words in sorted order.
The problem I seem to be having is that the program will accept words but when I enter the empty word it goes to a new line and nothing happens. An help or advice would be greatly appreciated. here is my code so far.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define LEN 20
#define LIM 20
int read_line(char str[], int n);
void sort_str(char *list[], int n);
int alpha_first(char *list[], int min_sub, int max_sub);
int main(void)
{
char *list[LIM];
char *alpha[LIM];
char word_str[LEN];
int word, i, j, num_count = 0;
for(;;){
printf("Enter a word: ");
scanf("%s", &word);
if(word == NULL)
break;
else
read_line(word_str, LEN);
list[i] = malloc(strlen(word_str) + 1);
strcpy(list[i], word_str);
alpha[i] = list[i];
}
sort_str(alpha, i);
for(i = 0; i < num_count; ++i){
printf("Sorted: ");
puts(list[i]);
}
return (0);
}
int read_line(char str[], int n)
{
int ch, i = 0;
while ((ch = getchar()) != '\n')
if (i < n)
str[i++] = ch;
str[i] = '\0';
return i;
}
void sort_str(char *list[], int n)
{
int i, index_of_min;
char *temp;
for (i= 0; i < n - 1; ++i) {
index_of_min = alpha_first(list, i, n - 1);
if (index_of_min != i) {
temp = list[index_of_min];
list[index_of_min] = list[i];
list[i] = temp;
}
}
}
int alpha_first(char *list[], int min_sub, int max_sub){
int i, first;
first = min_sub;
for(i = min_sub + 1; i <= max_sub; ++i){
if(strcmp(list[i], list[first]) < 0){
first = i;
}
}
return (first);
}
Your logic flow is flawed. If a word is entered, the scanf() will eat it from stdin and store a null-terminated string at the address of the integer 'word'. Any more than 3/7 chars entered, (32/64 bit, allowing for the null terminator), will start corrupting the stack. read_line() will then only have the line terminator to read from stdin, (assuming the UB doesn't blow it up first).
The problem I seem to be having is that the program will accept words but when I enter the empty word it goes to a new line and nothing happens.
There are several problems with this:
char word_str[LEN];
int word, i, j, num_count = 0;
/* ... */
scanf("%s", &word);
if(word == NULL)
break;
First, scanf("%s", &word) scans whitespace-delimited strings, and to that end it skips leading whitespace, including newlines. You cannot read an "empty word" that way, though you can fail to read a word at all if the end of the input is reached (or an I/O error occurs) before any non-whitespace characters are scanned.
Second, you are passing an inappropriate pointer to scanf(). You should pass a pointer to a character array, but you instead pass a pointer to an int. It looks like maybe you wanted to scan into word_str instead of into word.
Third, your scanf() format does not protect against buffer overflow. You should provide a field width to limit how many characters can be scanned. Moreover, you need to be sure to leave room for a string terminator.
Fourth, you do not check the return value of scanf(). If it fails to match any characters to the field, then it will not store any. Since it returns the number of fields that were successfully scanned (or an error indicator), you can detect this condition.
One way to correct the scanf() and "empty word" test would be:
int result;
result = scanf("%*[ \t]%19[^ \t\n]", word_str);
if (result < 1) break;
(That assumes a fixed maximum word length of 19 to go with your declared array length of 20.) You have several additional problems in your larger code, large among them that read_line() attempts to read the same data you just read via scanf() (in fact, that function looks altogether pointless). Also, you never update num_count, and after calling sort_str() you lose track of the number of strings you've read by assigning a new value to variable i.
There may be other problems, too.

Append numbers in C

How can I read six digits separately, and then append them?
For example:
I want to enter the following digits: 2 3 6 , 7 5
And the expected output would be: "236,75".
I have to do it with only one loop (to read the numbers), and I have to read the numbers with the type char.
Here's what I have so far:
#include <stdio.h>
int main()
{
char c;
char string [6];
printf("Introduce a number\n");
int i = 0;
while (i <=5) {
scanf("%c", &c);
string[i] = c;
i++;
}
printf("%c\n",string);
}
Try something like this:
char string [7];
printf("Introduce a number\n");
int i = 0;
while(i <=5){
scanf("%c", &c);
string[i] = c;
i++;
}
string[i] = '\0';
//printf("%s", string);
I added the '\0' character at string[6], just in case you need that for printing the values for example.
Also, I recommend you to read about cleaning the input buffer when obtaining input from stdin. Hope it helps.
For starters ensure that your int main() is actually returning an integer.
#include <stdio.h>
int main()
{
char c;
char string[7];
char* stringy = string;
printf("Introduce a number\n");
int i = 0;
while (i <=5) {
scanf("%c", &c);
string[i] = c;
i++;
}
string[i] = '\0';
printf("%s\n",stringy);
return 0;
}
Also you want to print your entire string out with a %s format specifier. This also means that you'll need to null terminate your string which can be done by setting the last character in your array to \0.
Also make sure your array has 7 indexes instead of 6, so everything can fit.
#include <stdio.h>
int main()
{
char c;
char string [7];
printf("Introduce a number\n");
int i = 0;
while (i <=5) {
scanf("%c\n", &c);
string[i] = c;
i++;
}
string[i] = '\0';
printf("result: %s\n",string);
return 0;
}
C strings end with a null character, that is '\0'. Therefore you should always append the null character to a character string as the last character since it determines the end of the string. Therefore the line string[i] = '\0'; is necessary (at the end of the while loop, the value of i will be 6, thus pointing to the last element of the character array).
Another correction to your code is the final printf(). You specified the format to be character format ("%c"), which will only output the first character of the string. You should change it to "%s" for printing the whole string.
This program should work since it is a valid C code. If you are having troubles with this code, then it is platform specific. I couldn't run this code on VS2012, but managed to run it on a GNU C Compiler. Try running the code on an online C compiler, it should work just fine.

Resources