I wanted to write a code which makes a uppercase of first letter of string 1 and 3 and printing those.
I tried the code below this but compiler gives İNVALİD CONVERSİON OF CHAR TO İNT
What is wrong with this code should i try with strlen and for loop?
This is code;
int main()
{
char str1[] = "elektrik";
char str2[] = "ve";
char str3[] = "elektronik";
str1 = toupper(str1);
str3 = toupper(str3);
printf("%s %s %s",str1,str2,str3);
getch();
return 0;
}
You need
*str1 = toupper(*str1);
...
Asssuming that str1 is a pointer to char (and include the appropriate header files)
Related
This must be a simple problem about char data type and pointers.
void main() {
const char* a;
char character = 65;
a = &character;
printf("%c \n", character); // PRINTS 'A' AS EXPECTED
if (strstr("ABC", a)) {
printf("found \n");
}
else {
printf("not found\n"); // goes into else
}
}
I don't understand why it doesn't go into first if statement.
You need to null terminate the a string so that it's a proper C string before calling strstr:
Any of the following:
if (strstr("ABC", "A"))
{
// found
}
Or
char a[2] = {'A', '\0'};
if (strstr("ABC", a))
{
// found
}
Or
const char* a = "A";
if (strstr("ABC", a))
{
// found
}
a is not a string. It is because strings in C need to be null terminated. By null terminated, I mean it's last element should be 0. It's so that when you pass strings to functions, then he functions can know when the string ends. The null terminating 0 is used to mark the end of a string.
You need to do:
char *a;
char character[2];
character[0] = 'A'; //Don't use 65. ASCII isn't the only encoding
character[1] = '\0';
a = character; //a is useless, you can pass character directly
Now, pass it: strstr("ABC", a)`. The above method is very bad, don't use it. Do one of these in practice:
char a[2] = "A"; //This will null terminate for you
//OR
const char *a = "A";
//OR
char a[2] = {'A', '\0'};
Using any one of these declarations, strstr should work.
This is my code. I am trying to simulate strcpy(). This code works, but I have a couple questions.
#include <stdio.h>
#include <stdlib.h>
char *strcpy(char *d, const char *s);
int main()
{
char strOne[] = "Welcome to the world of programming!";
char strTwo[] = "Hello world!";
printf("String One: %s\n", strOne);
printf("String Two before strcpy(): %s\n", strTwo);
strcpy(strTwo, strOne);
printf("String Two after strcpy(): %s\n", strTwo);
return 0;
}
char *strcpy(char *d, const char *s)
{
while (*s)
{
*d = *s;
d++;
s++;
}
*d = 0;
return 0;
}
When *s gets incremented to the position where '\0' is stored in the array, is that when the while condition becomes false because of '\0'? Does while read '\0' or just '0'?
'while' condition will be true if it reads '1'. All previous values of *s should be read as single characters in while condition, but the loop executes anyways. Why does this happen? Do all the single characters from the array *s is pointing equate to the value '1'?
What does *d = 0; exactly do? The way I understand it, the copying process is completed when the while loop is exited. So why does removing *d = 0 lead to an incorrect output being displayed?
Output without *d = 0 :
String Two before strcpy(): Hello world!
String Two after strcpy(): Welcome to the world of programming! programming!
Output with *d = 0 :
String Two before strcpy(): Hello world!
String Two after strcpy(): Welcome to the world of programming!
The characters in the ASCII table assume values that range from 0 to 127, 0 being NULL or '\0', so the condition is always true unless the character is '\0'.
*d = 0 places a '\0' at the end of the string; it's how strings are terminated in C. If you don't terminate the string, anything can be printed past the end of the string, and the program has no way to know where it ends. It's undefined behaviour.
Some more remarks. You return 0 instead of pointer to char. You should get some warnings. Return the copy instead. BTW this function can be simplified a bit as well.
char *strcpy(char *d, const char *s)
{
char *saved = d;
while ((*d++ = *s++));
return saved;
}
I am currently trying to handle string in C and I am having trouble placing the split values of a string into an array. Bellow is the code I have created in an attempt to achieve this.
#include <stdio.h>
#include <string.h>
int main(){
char str[]="titanic.txt";
char parts[2][5];
char *name = strtok(str, ".");
for (int i = 0; i < 2; i++){
parts[i][5] = name;
char name = strtok(NULL, ".");
}
printf("%c\n", str[0]);
return 0;
}
The output I would be expecting from this would hopefully look something like this.
char part[2][10]{
{'t', 'i', 't', 'a', 'n', 'i', 'c'},
{'t', 'x', 't'}
};
alternatively, I have tried something like this using string copy as such.
#include <stdio.h>
#include <string.h>
int main(){
char str[]="titanic.txt";
char parts[2][10];
char *name = strtok(str, ".");
for (int i = 0; i < 2; i++){
strcpy(parts[i], name);
name = strtok(NULL, ".");
}
printf("%s\n", parts[1]);
return 0;
}
Which, did what I want it to, but I would like to try and achieve this without string copy because I feel it will help me understand strings, characters, and arrays better. I do not want to reinvent the wheel I just want a deeper understanding.
The parts array should be an array of pointers, not a 2-dimensional array of characters:
char *parts[2];
Then you assign:
parts[i] = name;
If you want to copy from the input string to parts, you need to declare the 2nd dimension large enough for the largest possible string:
char parts[2][10];
and then you should use strcpy() rather than assignment to copy it.
strcpy(parts[i], name);
Notice that you don't give a second index to parts when doing this, that's only used to access specific characters of the string, not the string as a whole.
In case separating a file name from its extension is actually relevant to whatever you're trying to accomplish, I'll assume you're using Windows and point you to the documentation for the recommended Windows API library for this, <pathcch.h>.
With regard to your actual question, your first code doesn't work because:
You're assigning to a single character in the line parts[i][5] = name;. You're also overflowing since parts[i] has the type char [5], which only has positions 0 to 4.
You redeclare name as a single char rather than a char * pointer, which is the correct type, and was declared as such (correctly) outside the loop scope. Your new variable char name overwrites the existing char *name variable.
You cannot get around using strcpy-family functions to assign to a character array for this (and most other) use cases. The only time the syntax char foo[] = "Hello World"; is valid is immediately on declaration. Also, string literals are stored in read-only memory.
Following your coding style, this is the solution:
#include <stdio.h>
#include <string.h>
int main()
{
char str[] = "titanic.txt";
char delim[] = ".";
char parts[2][10];
char *ptr = strtok(str, delim);
int i = 0;
for (i = 0; i < 2; i++){
if(ptr != NULL)
{
snprintf(parts[i], sizeof(parts[0]) ,"%s", ptr);
ptr = strtok(NULL, delim);
}
}
printf("'%s'\n", parts[0]);
printf("'%s'\n", parts[1]);
return 0;
}
I am working on a initials project where you enter a name and it prints the initials. When I try and combine the strings it returns Segmentation fault instead of the initials.
#include <stdio.h>
#include <stdlib.h>
#include <cs50.h>
#include <string.h>
#include <ctype.h>
int main(void) {
printf("Name: ");
string name = GetString();
printf("\n");
int length = strlen(name);
string initials = "";
int arraylength = length + 1;
char string[arraylength];
string[0] = toupper(name[0]);
int count = 1;
for(int l = 1;l<=length;l++) {
if(name[l] == ' ') {
l++;
count++;
string[l] = toupper(name[l]);
}
}
count++;
string[count] = '\0';
for(int c = 0;c<=count;c++) {
strcat(initials, &string[c]);
}
printf("%s\n", initials);
}
That's why a string type would cause confusion, you make a pointer to a single char. And you then pass it to strcat() that's simply wrong.
A string, as expected by strlen() or strcat() or all str* functions, is not simple a char pointer which is what the type string in your code is.
In c a c-string is actually a sequence of bytes with the last byte being '\0', and it's not optional. You create a pointer to a single char and that is not the same as a string that I just described.
Any of the str* functions will try to find the '\0' but since you passed the address of a stack variable which is not an array, the behavior is undefined when any of these functions try to increment and dereference the passed pointer.
When you do understand how strings work in c you would see that using strcat() for the concatenation of many chunks of a large string together is not very efficient, you would also know that you just need to append a single char and that you can by simply using index notation, like
char string[8];
string[0] = 'E';
string[1] = 'x';
string[2] = 'a';
string[3] = 'm';
string[4] = 'p';
string[5] = 'l';
string[6] = 'e';
string[7] = '\0'; // The very necessary terminator
#include<stdio.h>
#include<string.h>
int main()
{
char c='g';
char d[]="John ";
strcat(d,&c);
puts(d);
return 0;
}
The output is:
John gC
The 'C' wasn't required.
Also, what does const char* mean here?
char *strcat(char *dest, const char *src)
Also, is a statement like this (inside a loop) wrong somewhere if I wish to add a character at the end of string?
char arr[]=' ';
symb[]={'a','b','c'}
strcat(arr, &symb[k]);
k++;
You are writing out of the bounds of d, you need room for one more char, change to
char d[7] = "John ";
or (if you don't want to specify the size of the array):
char d[] = "John \0";
or
char d[] = {'J', 'o', 'h', 'n', ' ', '\0', '\0'};
Also strcat wants a valid NUL terminated string and you are passing a pointer to a single char, change to
char *c= "g";
Two ways(there are even more):-
1>
char *c="g";
char d[10]="John ";
strcat(d,c);
2>
char c[]="g";
char d[10]="John ";
strcat(d,c);
Though I advise d[10] = {0} ; and then copy the string. (as David mentioned in comments.)
You need to learn the basics of C and C-style strings. Specifically, that a special zero-value character identifies the end of the string.
You have copied over the string but you did not copy the terminator. Therefore, functions like puts() don't know when to stop and print other characters that happen to be in memory.
There is undefined behaviour in your program . strcat requires null terminated string as its arguments where c is not . You can do this-
char c[]="g";
char d[7]="John "; // leave space for 'g' as well as for '\0'
strcat(d,c); // then pass both to strcat
Another way is to use sprintf -
char c[]="g";
char d[10]="John";
size_t n =strlen(d);
sprintf(&d[n]," %s",c);
This works: ( if you wanted John g )
#include<stdio.h>
#include<string.h>
int main()
{
char c='g';
char d[10];
char temp[2];
strcpy(d ,"John ");
temp[0]=c;
temp[1]='\0';
strcat( d , temp );
puts(d);
return 0;
}
This works: ( if you wanted Johng )
#include<stdio.h>
#include<string.h>
int main()
{
char c='g';
char d[]="John ";
//strcat(d,&c);
d[strlen(d)-1]=c;
puts(d);
return 0;
}