Jump to content

How to return string to variable in C?

duckwithanokhat

I'm not sure what you want to achieve. Do you want your function to return a value whenever it's invoked?

Link to comment
Share on other sites

Link to post
Share on other sites

Just now, Lehti said:

I'm not sure what you want to achieve. Do you want your function to return a value whenever it's invoked?

So to keep it short, I have an input function called input, and a char variable called char unit1 [20];

 

In the input function, I am inputting a string to the chat variable in that function and trying to return it to unit1

 

But for some reason the line:

unit1 = input(unit1);

is giving me erroes

Link to comment
Share on other sites

Link to post
Share on other sites

I bet that's because unit1 is still empty. Use another variable as argument for input.

EDIT: Also, does input end with something like

	return variable
}

?

Link to comment
Share on other sites

Link to post
Share on other sites

Just now, Lehti said:

I bet that's because unit1 is still empty. Use another variable as argument for input.

Wait, maybe I'm the one confused but, unit1 is empty because I want to assign it a string with my input function.

 

If I'm wrong, what would/could I use?

Link to comment
Share on other sites

Link to post
Share on other sites

It's a bit hard to tell without knowing what your code is supposed to do, but essentially you're asking the program "hey, take the empty array of characters unit1, do some magic and return a certain value (which is going to be an empty array anyway) and assign it to the empty array unit1".

Link to comment
Share on other sites

Link to post
Share on other sites

5 minutes ago, Lehti said:

It's a bit hard to tell without knowing what your code is supposed to do, but essentially you're asking the program "hey, take the empty array of characters unit1, do some magic and return a certain value (which is going to be an empty array anyway) and assign it to the empty array unit1".

Huh, my code is supposed to convert meters to km or km to meters, and so if I want to return a value should I initialize the variable with an array and then can I overwrite it?

 

Edit: Nope that didn't work

Link to comment
Share on other sites

Link to post
Share on other sites

Uhm... Why using strings then? You're overcomplicating something that's actually trivial to accomplish without functions.

In pseudo code, you'd need to do something like:

unit1 = ""
while unit1 not "km" or unit1 not "m"
  print "What unit of measurement you want to convert from?\n"
  read unit1
if unit1 == "km" then
  print "Insert your length in kilometers"
  read number
  result = number*1000
  print unit1, " is ",result," meters\n"
else
	print "Insert your length in meters"
  read number
    result = number/1000
    print unit1, " is ",result," kilometers\n"
return 0

 

Link to comment
Share on other sites

Link to post
Share on other sites

1 minute ago, Lehti said:

Uhm... Why using strings then? You're overcomplicating something that's actually trivial to accomplish without functions.

In pseudo code, you'd need to do something like:


unit1 = ""
while unit1 not "km" or unit1 not "m"
  print "What unit of measurement you want to convert from?\n"
  read unit1
if unit1 == "km" then
  result = unit1*1000
  print unit1, " is ",result," meters\n"
else
    result = unit1/1000
    print unit1, " is ",result," meters\n"
return 0

 

Yea, I'm a highschool student trying to learn the tricks of the trade lol. I just learned about functions, so I guess I'm a bit too over hyped about them. Btw, what does the "while" do and "read"?

Link to comment
Share on other sites

Link to post
Share on other sites

They're not actual commands, it's written in pseudo-code, that is, normal language "dressed up" as a programming language. I just noticed I made a mistake in it, though, lemme fix it.

Link to comment
Share on other sites

Link to post
Share on other sites

1 minute ago, Lehti said:

They're not actual commands, it's written in pseudo-code, that is, normal language "dressed up" as a programming language. I just noticed I made a mistake in it, though, lemme fix it.

I know what psuedocode is, but yea I guess I over complicated something simple.

 

3 minutes ago, duckwithanokhat said:

else result = unit1/1000 print unit1, " is ",result," meters\n"

Question about this line (quoting code seems to be not that great).

Does the else assume that the user types in meters instead of kilometers, what if the user types in something random?

Link to comment
Share on other sites

Link to post
Share on other sites

Okay, now it's fixed. While is a type of iteration (a cycle) that keeps repeating until a condition is met. In your case, your program ONLY accepts "km" or "m" as input for unit1, so you can use a while statement to keep asking the same question over and over again until the user answers appropriately. read is essentially scanf.

Link to comment
Share on other sites

Link to post
Share on other sites

I'm sorry to ask you so many questions, but here is my revised code, at least the most important parts:

char unit1[20];
float val_m;
float val_km;

puts("What do you want to convert? Meters or kilometers?");
printf("Please type in either 'm' or 'km': ");
scanf("%s", &unit1);

if (unit1 == "m")
    {
        puts("Please input the meter value");
        scanf("%f", &val_m);
        val_km = val_m * 1000;
    }

printf("%s", val_km); //Temporary to see if my calculations work

When I run and input I get (null) and can't do anything else, what is wrong with the code?

Link to comment
Share on other sites

Link to post
Share on other sites

No idea, I'm not a C coder. My experience is limited to Python and some Pascal.

Link to comment
Share on other sites

Link to post
Share on other sites

Just now, Lehti said:

No idea, I'm not a C coder. My experience is limited to Python and some Pascal.

Oh. lol

Link to comment
Share on other sites

Link to post
Share on other sites

Your best bet is asking at programmers.stackexchange.com

It's chock full of very knowledgeable people that will surely explain everything you need to know. :)

Link to comment
Share on other sites

Link to post
Share on other sites

Just now, Lehti said:

Your best bet is asking at programmers.stackexchange.com

It's chock full of very knowledgeable people that will surely explain everything you need to know. :)

Noted, while I did fix the null problem now my condition in my if statement isn't being met, I have problem after problem lol xD

 

Link to comment
Share on other sites

Link to post
Share on other sites

I don't program in C much, but generally using "==" to compare strings is bad. It's fine for integers, or chars. 

 

Use strcmp() instead - a simple google search will tell you exactly how to use it, and if you still have problems with the condition (or how to use the function), then I'll be happy to assist further.

 

 

 

On a side note, one thing I noticed in your code above is the line:

printf("%s", val_km);

Notice that you use %s, and val_km is of type float. You use %s only for strings, so this shouldn't work. Replace %s with %f instead if you'd like to print floats out :)

"The only person you are destined to become is the person you decide to be."


CPU: Intel i5 4690K - Motherboard: Asus Maximus VII Ranger - RAM: Corsair Vengeance LP - 2x4GB @ 1866Mhz - GPU: MSI Twin Frozr GTX 770 4GB - CPU Cooler: Be Quiet! Dark Rock Pro 3 CPU Cooler - PSU: EVGA SuperNova G2 750W - Storage: Seagate Barracuda 2TB HDD- Case: Fractal Design Define R4 Windowed (with Red AKASA Led Strips) - Display: Benq GL2460HM 24" Monitor

Link to comment
Share on other sites

Link to post
Share on other sites

1 minute ago, Tazman192 said:

I don't program in C much, but generally using "==" to compare strings is bad. It's fine for integers, or chars. 

 

Use strcmp() instead - a simple google search will tell you exactly how to use it, and if you still have problems with the condition, then I'll be happy to assist further. One thing I noticed in your code above is the line:


printf("%s", val_km);

Notice that you use %s, and val_km is of type float. You use %s only for strings, so this shouldn't work. Replace %s with %f instead if you'd like to print floats out :)

Finished my code already, I did end up using strcmp(), but appreciate the help anyways.

Link to comment
Share on other sites

Link to post
Share on other sites

3 minutes ago, duckwithanokhat said:

Finished my code already, I did end up using strcmp(), but appreciate the help anyways.

No problem. 

 

If you're just starting out learning how to program, I'd generally advise learning C first. It can get difficult with memory access, pointers, no garbage collections and what not. If you have a choice, program in Python or Java to learn the basics first.

 

If you learn an object-oriented language first, in my opinion learning an imperative language like C is much more straightforward.

"The only person you are destined to become is the person you decide to be."


CPU: Intel i5 4690K - Motherboard: Asus Maximus VII Ranger - RAM: Corsair Vengeance LP - 2x4GB @ 1866Mhz - GPU: MSI Twin Frozr GTX 770 4GB - CPU Cooler: Be Quiet! Dark Rock Pro 3 CPU Cooler - PSU: EVGA SuperNova G2 750W - Storage: Seagate Barracuda 2TB HDD- Case: Fractal Design Define R4 Windowed (with Red AKASA Led Strips) - Display: Benq GL2460HM 24" Monitor

Link to comment
Share on other sites

Link to post
Share on other sites

4 minutes ago, Tazman192 said:

No problem. 

 

If you're just starting out learning how to program, I'd generally advise learning C first. It can get difficult with memory access, pointers, no garbage collections and what not. If you have a choice, program in Python or Java to learn the basics first.

 

If you learn an object-oriented language first, in my opinion learning an imperative language like C is much more straightforward.

Yea I'm learning C in my high school course, so I got no choice whether I like it or not. Although I heard my school's ap computer science course teaches java. 

Link to comment
Share on other sites

Link to post
Share on other sites

On 8.10.2016 at 10:19 AM, duckwithanokhat said:

How do I return a string inputted using scanf, in a function, to a variable on main()?

One gives a pointer to the char array as an argument to the function so the function can write to it.

For example:

 

void GetString(char *Destination)
{
	scanf("%s", Destination);
}

//Which can now be called as such...

char Unit1[20];
GetString(Unit1);

Do note tough that scanf is unsafe. If the user inputs more then 19 (20 - 1 for terminating 0) characters, scanf will write into memory beyond Unit1 and crash the program or cause bugs. One common method is to always use fgets when user input is required as fgets allows you to set a maximum amount of characters to be read.

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×