Getting a string in c++ from user, and displaying it - c++

how do i do it??
it tried this code:
char num[10];
printf("Enter num:");
scanf_s ("%s", &num);
printf("\n%s \n", num);
ignore 'num' please..
i use VS 2013, and my only included library is "stdafx.h"

See std::getline.
In C++, don't use printf, use std::cout.
Don't use char[], use std::string.

If you selected the type of the project like console application and compile it as a C++ program then the code can look the following way
#include "stdafx.h"
#include <iostream>
int _tmain(int argc, _TCHAR* argv[])
{
char s[100];
std::cout << "Enter a sentence: ";
std::cin.getline( s, sizeof( s ) );
std::cout << "You entered \"" << s << "\"\n";
return 0;
}

You don't you use the "string" in c++ instead of the char array. Its easy for operation and maintenance, plus its much more simple and efficient with so many built in algorithms.
string num ;// instead of char num[10];
cout<<"Enter num";
cin>>num;
cout<<num;
you may use printf or scanf. Thats completely ok

Related

Making array (char) 1 gives error on stdio.h

I was trying to hold the text entered by user inside an Char array but it does not end up well. I tried this method but i think it deleted after c++ 11.
Here's my code :
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
char sentence[2];
cout << "Enter your sentences : ";
gets_s(sentence);
cout << sentence << endl;
system("PAUSE");
return 0;
}
It gives overload error and doesnt works.
Chances are you are trying to get the string literal that is longer than 2 characters yet not being able to insert it into your buffer of:
char sentence[2];
Increase the buffer size to something more acceptable:
char sentence[255];
That being said in C++ you should prefer std::string to character array and std::getline to gets_s.

Character Array of dynamic length

I have written a C++ Function which can be represented as below:
All it does is take a string (this is where it crashes) and reverse it.
#include <iostream>
#include <string.h>
#include <stdio.h>
using namespace std;
int main()
{
cout<<"Enter a string: "<<endl;
char *str;
gets(str);
cout<<"Reversed String is: ";
for(int i=strlen(str)-1;i>=0;i--)
cout<<(str[i]);
return 0;
}
I guess there's some kind of memory access violation.
Any clue why this doesn't work?
Error: Segmentation fault (core dumped)
In c++ there is way more easier and less error prone solution to this problem via std::reverse from algorithm. Also its easier to use std::string.
#include <iostream>
#include <algorithm>
int main ()
{
std::string input;
std::cout << "Enter string to reverse: ";
std::cin >> input;
std::reverse(input.begin(),input.end());
std::cout << "Reversed string: " << input << std::endl;
return 0;
}
If you have to do it via char arrays, try this (you dont even need dynamic memory allocation)
#include <iostream>
#include <algorithm>
#include <cstring>
int main ()
{
char input[1024];
puts("Enter string to reverse: ");
fgets(input, 1024, stdin);
std::reverse(input, input + strlen(input));
printf("Reversed string: %s", input);
return 0;
}
Your code isn't c++ style and I recommend you take a look at the answer from Filip (https://stackoverflow.com/a/45903067/4386427)
I'll just address what goes wrong with your code.
When you do
char* str;
all you get is a pointer that can point to a char. You don't get any memory for holding a char. Further the value of the pointer variable str is uninitialized.
So when you do
strlen(str)
you read an uninitialized variable and try to treat this uninitialized value as a C-style string. That is undefined behavior and is very likely to cause a program crash.
You need to make sure that str is initialized before using it. As you want dynamic memory, you could do:
char *str;
str = new(char[100]); // Initialize str to point to a dynamic allocated
// char array with size 100
...
...
delete(str);
But again - I wouldn't use this style in c++ code

C++ input multiple words to string

I've tried using getline(), but the problem is that i have this in loop, and the program simply doesn't stop to get the inputs like it normally does when using cin.
Here's how my code looks like:
for (int i=0; i<value; i++){
cout<<endl<<"what are You saerching for?";
getline(cin, searchFor[i]);
cout<<"How it should be changed?";
getline(cin, changeTo[i]);
}
It works normally using cin, but that way i can't get more than 1 word to the table (both tables are strings).
You could simply use scanf to do this.
Here is a little example that ask the user to type text, then print the user entry on "enter" key press
#include <iostream>
#include <stdio.h>
int main(int argc, char **argv){
char buf[2048];
std::cout << "enter something" << std::endl;
scanf("%[^\t\n]", buf);
printf("Your input : %s\n", buf);
return 0;
}
Note In that example, buf is only 2048 bytes, this means that a user could enter more than 2048 caracters, and break this little code with a seg fault, be safe with strings.

New to c++; Entering and displaying name in C++

I'm very new to c++, I can enter a name, but it doesn't display correctly. My tutor told me to research strings, and when I did none of it made any sense.
#include<stdio.h>
#include<string.h>
main()
{
char name;
printf("Hello stranger, what is your name?\n");
scanf("%c\n", &name);
system("PAUSE");
printf("\n\nWelcome to the Town of Falls Creek, %c\n",name);
}
In C++, we use std::string for sequences of characters. And we use std::cout and std::cin instead of printf and scanf
Be sure to look at this on internet, you will find a lot of resources.
char name;
scanf("%c\n", &name);
is a C-style approach to read a single character from standard input.
What you should do is:
#include <iostream>
#include <string>
...
std::string name;
if (std::cin >> name)
std::cout << "Hello " << name << "." << std::endl;
You used a char as the variable for the name.
char name;
This is where you need to uses string.
Btw: You code would look more like modern c++
if you would use std::cin instead of scanf.
char can take only single character like 'a', 'b' etc... So use string data type there.
It doesnt show you the total name because you are using char.
Instead of char use string.
#include<stdio.h>
#include<string.h>
#include<conio.h>
main()
{
std::string name;
printf("Hello stranger, what is your name?\n");
scanf("%s\n", &name);
getch();
printf("\n\nWelcome to the Town of Falls Creek, %s\n",name);
}
Enjoy coding!

itoa function problem

I'm working on Eclipse inside Ubuntu environment on my C++ project.
I use the itoa function (which works perfectly on Visual Studio) and the compiler complains that itoa is undeclared.
I included <stdio.h>, <stdlib.h>, <iostream> which doesn't help.
www.cplusplus.com says:
This function is not defined in ANSI-C and is not part of C++, but is supported by some compilers.
Therefore, I'd strongly suggest that you don't use it. However, you can achieve this quite straightforwardly using stringstream as follows:
stringstream ss;
ss << myInt;
string myString = ss.str();
itoa() is not part of any standard so you shouldn't use it. There's better ways, i.e...
C:
int main() {
char n_str[10];
int n = 25;
sprintf(n_str, "%d", n);
return 0;
}
C++:
using namespace std;
int main() {
ostringstream n_str;
int n = 25;
n_str << n;
return 0;
}
Boost way:
string str = boost::lexical_cast<string>(n);
itoa depends on compiler, so better use the following methods :-
method 1 :If you are using c++11, just go for std::to_string. It will do the trick.
method 2 :sprintf works for both c & c++.
ex-
ex - to_string
#include <bits/stdc++.h>
using namespace std;
int main ()
{
int i;
char buffer [100];
printf ("Enter a number: ");
scanf ("%d",&i);
string str = to_string(i);
strcpy(buffer, str.c_str());
cout << buffer << endl;
return 0;
}
Note - compile using -std=c++0x.
C++ sprintf:
int main ()
{
int i;
char buffer [100];
printf ("Enter a number: ");
scanf ("%d",&i);
sprintf(buffer, "%d", i);
return 0;
}`
you may use sprintf
char temp[5];
temp[0]="h"
temp[1]="e"
temp[2]="l"
temp[3]="l"
temp[5]='\0'
sprintf(temp+4,%d",9)
cout<<temp;
output would be :hell9
Did you include stdlib.h? (Or rather, since you're using C++, cstdlib)