Converting the output of a void method to String in C [closed] - c

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have written a void function which takes an unsigned int. Then I call this in the main function. I want the output to be a string so that I can include it in the printf statement for formatting reasons. But since I'm calling a void function, I can't tell printf that its a string (%s) or an int (%d). How can I take the output from this called void function in my main and turn it to some kind of string or integer?

A function declared as e.g. void foo(int); has no result. So you cannot convert its inexistent result to an integer or to a string.
notice that C does not have stricto sensu a string datatype. You use pointer to memory zones made of char, with the convention to zero-terminate strings.
Perhaps you want to get the output (done using printf, fprintf, fputs, and other stdio(3) standard library functions) of a function as a string. On Linux (and GNU libc) systems, you could use open_memstream(3)
Do not confuse the output of a function with its result!
So suppose you have written some outputing function like e.g.
void show_x(FILE*out, int x) { fprintf(out, "x=%d\n", x); }
Then you could get that into a string like ptrbuf (on Linux) using:
char*ptrbuf=NULL;
size_t sizbuf=0;
FILE* outmem = open_memstream(&ptrbuf, &sizbuf);
if (!outmem) { perror("open_memstream"); exit(EXIT_FAILURE); };
show_x(outmem, 42);
fflush(outmem);
printf ("now ptrbuf is %s\n", ptrbuf);
fclose(outmem);
// you later should free the `malloc`-ed `ptrbuf`
free (ptrbuf), ptrbuf=NULL;
sizbuf=0;

A void function returns nothing. Change its return type to be const char* to return a C-string:
#include <stdio.h>
const char* func_that_returns_string(unsigned int x)
{
switch (x) {
case 0: return "zero";
case 1: return "one";
default: return "who needs any other numbers?";
}
}
int main(void)
{
int i = 3;
const char* str;
str = func_that_returns_string(i);
printf("%d: %s\n", i, str);
return 0;
}

Related

How do I split a string in function in C? [duplicate]

This question already has answers here:
C's strtok() and read only string literals
(5 answers)
Closed 3 years ago.
I need a function that split a string in c, i write the code and I checked it, I didn't get any errors or warnings, the code is :
int main()
{
cutString("any#any#any5") ;
return 0;
}
void cutString(char query[2000]) {
char * cut ;
cut = strtok(query , "#") ;
printf("%s" , cut);
}
But when I compile the program the compiler get stuck, without showing any output.
This is a picture for run screen.
Pay attention to the usage of strtok(). According to the Linux Man Page, on the first invocation of the function, you should specify the string to parse as first argument, while in each subsequent call you should specify NULL.
In fact, a sequence of calls on the same string maintains a pointer to the next character to process. If you want to check if no more tokens are found, just look at the return value (it'd be NULL in that case).
First of all you should read about the usage of strtok()
Please keep in mind you can't use strtok() on a string literal, since it will attempt to modify it which will cause undefined behavior.
#include <stdio.h>
#include <string.h>
int main()
{
char toCut[100] = "to#cut#this";
cutString(toCut);
return 0;
}
void cutString(char* query) {
char* cut ;
cut = strtok(query, "#"); // this first call returns a pointer to the first substring
while(cut != NULL)
{
printf("%s\n", cut);
cut = strtok(NULL, "#"); // each call to strtok returns a pointer to the next substring
}
}

C writing to string (specific function asked)

I am kind of in a pinch with searching one specific function with return type int which changes the values of a char array (string) by taking exactly 5 parametres whereas the function must not be imported from any other library with an exception of stdio.h maybe.
The source looks like in following:
#include <stdio.h>
int main() {
char buffer [50];
int n;
n= // some function here ;
printf("%s",buffer,n);
return 0;
}
I have been looking into many functions, but none I knew of or found match the above requirement such that I'd appreciate the help of more knowledgeable people now. Thanks in advance.
You have to go with functions with variable argument lists.
Two such ones in stdio.h are:
int sprintf(char * restrict s, const char * restrict format, ...);
int snprintf(char * restrict s, size_t n, const char * restrict format, ...);
Note: These functions do not exactly take five arguments as you specified in your question. They take a minimum number of arguments (2 & 3 respectively) but can go way beyond 5 arguments.
which changes the values of a char array (string)
The following does what you want to char array (info):
char info[60];
char name[] = "Christopher Westburry";
char designation[] = "Learner";
int reputation = 72;
sprintf(info, "Welcome %s to StackOverflow!\nDesignation: %s\nReputation: %d",
name, designation, reputation);
printf("%s", info);
Skimming Appendix B of the C Standard, I don't see anything that takes exactly 5 arguments and returns an int.
OTOH stdio.h is full of functions that return an int and take a variable number of arguments in the scanf and printf family. Once can contrive something. Since buffer is uninitialized, and the code wants to print it, presumably we're going to read something into it from stdin. That probably means some contrived scanf call.
#include <stdio.h>
int main() {
char buffer [50];
int n;
// Same as
// n = scanf("%40s", buffer);
n = scanf(
"%10s%10s%10s%10s",
buffer,
&buffer[10],
&buffer[20],
&buffer[30]
);
// printf("%s",buffer,n);
printf("'%s' %d\n",buffer,n);
return 0;
}
If that's the answer they expect, this exercise is pretty pointless.
Note that the printf in the original code has a bug where it's passed in too many arguments. Maybe that's a clue and this is supposed to be some clever use of Undefined Behavior?

Multiple call of char[] returning function for immediately fprint

I look for a comfortable way of converting a custom type variable to char[] (string) for the purpose of immediate fprinting. Here is what I intend to do, yet still flawed.
#include <stdio.h>
#include <string.h>
char * toStr (int);
void main (void) {
printf("%s , %s , %s \n", toStr(1), toStr(2), toStr(3));
}
char * toStr (int z) {
static char oS[100];
sprintf(oS, "%d", z);
printf("Will return: %s\n", oS);
return oS;
}
This will display
Will return: 3
Will return: 2
Will return: 1
1 , 1 , 1
I see what the problem is here, printf seems to print the content of static char oS once for all three calls in its parameterlist. It does not evaluate each call exactely when it is needed in the format string. But i need the static (as one possible way) to make the content of oS available outside of toStr.
I feel like I am almost there, of corse I want the output
1 , 2 , 3
on screen. Is there a possiblility to get what I want, without having to mallocate and free every part or storing each return of toStr in a sepearate variable just to fprint them aftwerwards? Isn't it possible to fprint the return values of the same function multiple times in one call?
Local static variables are shared between all invocations of the function. That means all calls will use the same buffer and return the same pointer to the same string.
And since the evaluation order of arguments is not specified (I don't remember if it's implementation defined, undefined, or just simply not specified), then you don't know which will be the last call (which will be the call the decides which the contents of the array will have).
The only thing you do know is that all arguments must be evaluated before the actual call to the function is made. Arguments and expressions are not evaluated lazily.
The order of evaluation of function arguments is unspecified. So printf doesn't necessarily evaluate it in any order you desire/expect.
As you debug prints show, toStr does write multiple value to oS. But all arguments of printf will be evaluated before the function call is made.
So the whatever the value written as will be value written by printf for all 3 arguments since the function toStr returns the pointer to the same object (oS in toStr).
Note that function-local static variables are error prone as it's not thread-safe.
But i need the static (as one possible way) to make the content of oS available outside of toStr.
It's not possible to achieve what you want in your current way. You can either ask toStr to allocate memory each time (save it in the caller and free it after use).
Or pass the buffer you to write to each time:
#include <stdio.h>
#include <string.h>
char *toStr(char *, size_t, int);
int main (void)
{
char s1[256];
char s2[256];
char s3[256];
/* could also use s[3][256]; instead 3 separate vars */
printf("%s , %s , %s\n", toStr(s1, sizeof s1, 1), toStr(s2, sizeof s2, 2), toStr(s3, sizeof s3, 3));
}
char *toStr(char *oS, size_t len, int z)
{
snprintf(oS, len, "%d", z);
printf("Will return: %s\n", oS);
return oS;
}
After 3 calls to the function printf prarameters point to the same static buffer - and this buffer contains (which obvious only the one information.
You can check the evaluation order of your implementation without printfs inside the function
#include <stdio.h>
#include <string.h>
char *foo(const int i)
{
static char c[200] = {0,};
sprintf(&c[strlen(c)], "i = %d ", i);
return c;
}
int main(void) {
printf("%s %s %s\n", foo(1), foo(2), foo(3));
return 0;
}

Why scanf() always return nothing? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
Hi i need help about this:
int t;
t = 1;
char abc[256];
int main() {
scanf("%s", abc);
if(abc == "google") {
printf("%s \n", abc);
system("firefox");
} else
printf("error");
}
it always return error please someone help!
i already tried scanf("%c", &abc); and i rewrote this about 5 times with the same result.
I'm new at this so this can be a very stupid thing.
if(abc == "google") {
This doesn't do what you think it does. This checks whether the pointers to those two strings are numerically equal. They never will be, because abc is allocated in the stack, and "google" is a string literal and therefore has static storage duration.
You should use strcmp like ameyCU points out.
In general, don't use scanf like this, the code you wrote is vulnerable to buffer overflow attacks if someone passes a large string.
You might want to look at this nice post about how to use scanf safely. How to prevent scanf causing a buffer overflow in C?
You can't compare the contents of two character arrays with ==. == will just compare the memory addresses of the arrays (after array-to-pointer decay).
Use strcmp instead:
if (strcmp(abc, "google") == 0) ...
The constant string "google" reside in the .rodata section of your program and if you compile with all warning -Wall you get this warning
google.c:10:12: warning: comparison with string literal results in unspecified behavior [-Waddress]
if(abc == "google") {
and this code is equivalent with
const char* const google_str = "google";
if(abc == google_str)
Here both the string "google" and the address to that string is constant. So you see you are doing a pointer comparison and not a string comparison.
printf("%p == %p\n", abc, google_str);
This code will show you that abc reside on the stack and that google_str reside in the .rodata section. String comparison should be done with
if(0 == strcmp(abc, "google")) {
<code>
if(abc == "google")
</code>
would work in object oriented languages like java and dot net
in c cpp you have to use inbuild library functions of String like strcpy,strcmp
<code> int strcmp(const char *str1, const char *str2) <code>
compares the string pointed to, by str1 to the string pointed to by str2.
So you will modify your code as
#include <stdio.h>
int t;
t = 1;
char abc[256],a[256];
int main()
{
strcpy(a,"google");
scanf("%s", abc);
if( strcmp("abc","google")==0 ) {
printf("%s \n", abc);
printf("firefox");
} else
printf("error");
return 0;
}

C Unexpected string returned from function behaviour [duplicate]

This question already has answers here:
returning a local variable from function in C [duplicate]
(4 answers)
Closed 7 years ago.
I am quite new to C and I am playing with some string operations. I have encountered quite a strange problem for me while returning a string from a function. My simple program is as follows:
int main(int argc, char* argv[])
{
char text[] = "abAB";
char* out = testString(text);
printf("Result Text: %s", out);
printf("\n");
}
char* testString(char* input) {
char* text = copyString(input);
return text;
}
The copyString function defines a simple operation to copy one string to another. It is as follows:
char* copyString(char* input) {
char output[100];
int index = 0;
while (input[index] != '\0') {
output[index] = input[index];
index++;
}
output[index] = '\0';
return output;
}
The problem is that while I am debugging the application, the string I am returning from a function seems to be OK (Visual Studio visualises it well enough) and when the printf line occurs, the string outputted on the stdout is something completely strange and unfamiliar - a smily face. Sadly, I can't post images yet in order to show you what I see in my console as output.
I am using Visual C++ Express 2010 as an IDE if this could be helpful.
You are returning a variable declared within a function, which will cease to exist outside the scope in which it is declared. Use a dynamically allocated char array and then return a pointer to it.
char* output = malloc(100 * sizeof(char));
...
return output ;
Note : You are assuming that input string is less than 100 characters. Instead of that, try passing the length of string as a parameter or use strlen. Your program will crash if input string has more than 99 characters.
Also as noted in comments, free the memory allocated when you are done using it.

Resources