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!
Related
I am trying to get the first character of a string written to a variable of type char. With std::cin (commented out) it works fine, but with scanf() I get runtime error. It crushes when I enter "LLUUUR". Why is it so? Using MinGW.
#include <cstdio>
#include <string>
#include <iostream>
int main() {
std::string s;
scanf("%s", &s);
//std::cin >> s;
char c = s[0];
}
scanf knows nothing about std::string. If you want to read into the underlying character array you must write scanf("%s", s.data());. But do make sure that the string's underlying buffer is large enough by using std::string::resize(number)!
Generally: don't use scanf with std::string.
Another alternative if you want to use scanf and std::string
int main()
{
char myText[64];
scanf("%s", myText);
std::string newString(myText);
std::cout << newString << '\n';
return 0;
}
Construct the string after reading.
Now for the way directly on the string:
int main()
{
std::string newString;
newString.resize(100); // Or whatever size
scanf("%s", newString.data());
std::cout << newString << '\n';
return 0;
}
Although this will of course only read until the next space. So if you want to read a whole line, you would be better off with:
std::string s;
std::getline(std::cin, s);
I need to convert a std::string to a const char*.
To do so, I used the c_str() method on the string, as in the following code :
#include <iostream>
#include <string>
using namespace std;
int main(void) {
string testStr;
cin >> testStr;
const char* testStrConst = testStr.c_str();
cout << testStrConst << endl;
return 0;
}
If I type "Hey hello" in the terminal, when this code is running, the output is only "Hey".
Why is the second word ignored?
Because it was never a part of the std::string in the first place.
The >> operator reads only a single, whitespace delimited word.
Use std::getline() instead of >> to read the entire line of text entered on standard input.
string testStr;
getline(cin, testStr);
I have tried a lot to debug my code but it is still not working.The whole code just crashes but there is no allover error I am presenting the code please try to debug that one.
Code:
#include <iostream>
#include<conio.h>
#include<string.h>
#include<fstream>
using namespace std;
void write(char fname[],char text[])
{
strcat(fname,".txt");
ofstream w(fname,ios::app);
w<<text;
w<<"\n";
w.flush();
w.close();
cout<<" sippy "<<fname<<" ";
}
int main ()
{
int login=0;
char t[100],id[100]="Its id ",pass[100]="Its password";
login=1;
strcpy(t,id);
strcat(t,"\n");
strcat(t,pass);
cout<<" finally ";
write("database",t);
getch();
strcpy(t,id);
getch();
cout<<t<<" showing t here";
getch();
cout<<" hope this works for now ";
getch();
cout<<"\nEnter the text"<<endl;
write(id,t);
}
The above mentioned code does not work on tdm gcc code blocks
Edit 1:
Ok so now the major problem has been detected it is a minor bug usually caused because of drawback of a bad programming style. As it is often suggested that if a string is passed to a function then that particular function allocates a new string at the memory of the passed string. Since the passed string is a literal the code editing the newly formed string would try to edit a read only literal memory which is an error
Literals are read only because if compiler finds the use of same literal at some different place then it would be able to use same memory to flash the contents of literal therefore it becomes a necessity to make a literal read only and use of c-style string carefully(rather std::string should be used)
Thanks to all
If you are facing a SegFault I think this line could be the problem :
write("database",t);
because in your write function you use strcat on fname but you pass a read-only string.
Also, I think it might be best to use real c++ instead of c+ like :
#include <string>
#include <iostream>
#include <fstream>
void my_write(std::sting & fname, std::string & text) {
std::string file = fname + ".txt";
std::osftream w(file, std::ios::app);
w << text << "\n";
w.flush();
w.close();
}
int main() {
std::string t = "";
std::string id = "Its id";
std::string pass = "Its password";
std::string fname = "database";
int login = 1;
t = id + "\n" + pass;
my_write( fname, t);
}
I haven't test it but the idea is here.
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
i am trying to create a simple (modularized) c++ program that reads the users input and spits it back out.
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void _printOut(char * output)
{
cout << output << endl;
}
char * readUserInput()
{
char userInput[256];
cin >> userInput;
return userInput;
}
int _tmain(int argc, _TCHAR* argv[])
{
_printOut("Enter your name: ");
char * userName = readUserInput();
_printOut("Hello");
_printOut(userName);
system("pause");
return 0;
}
Enter your name:
aaaa
Hello
╠╠╠╠╠╠╠╠
Press any key to continue . . .
if i print out the userInput variable in the readUserInput function it prints out what is inputted. However trying to print out the userInput variable store as userName in the _tmain function results in a incomprehensible sequence of chars being printed out. ie. ╠╠╠╠╠╠╠╠.
By my best guess, this could be caused by pointer issues, but as far as I can tell I am referencing everything correctly.
Debugging this code:
at this line: _printOut("Hello"); in method: _tmain [userName = "abcdefg"]
at this line: _printOut(userName); in method _tmain [userName = "†UX"]
so I am wondering how the value of username is changing when it isn't assigned or manipulated between the two lines.
char * readUserInput()
{
char userInput[256];
cin >> userInput;
return userInput;
}
The char userInput[256]; array only exists during the function call. Once you hit the bottom of the function it ceases to exist, and you return a pointer to some garbage memory.
This is called local scope.
And anyway, what if someone has a reaally long name (longer than 255 characters).
Consider using std::string, which will solve both problems.
std::string readUserInput()
{
std::string inp;
std::cin >> inp;
return inp;
}
and
void printOut (const std::string& toPrint)
{
std::cout << toPrint << '\n';
}
(Also, and this is less important, the name _printOut is not allowed in this context, because of the leading _. See here, although it might go over your head if you are a beginner.)
Edit An even better way to go is to use std::getline to read a whole line at a time into a std::string. However, because of the way they treat spaces, and in particular '\n' newline characters, getline(...) and cin>>... don't play nicely together. It's usually just best to pick one and stick with it throughout your program. Here's how readUserInput() would look:
std::string readUserInput()
{
std::string line;
std::getline(std::cin, line);
return line;
}
This way if a user enters a name containing whitespace (e.g. "BoB T. Fish") you will read the whole name, rather than just "BoB" (and then leaving the rest to confuse you the next time you read).
The reason this can be iffy to mix cin>>... with getline is that cin>>... will read as much as it can up to whitespace, then leave the rest behind. So apart from mayb emissing someone's surname, if they enter a name without spaces, it will just leave the last newline character on the input stream. Then when you come along and do getline, you don't get the next line of user input. You get the empty line that has been left behind. If you had instead used cin>> again, the newline would have been ignored.
e.g. Consider this user input:
Hello\n
World\n
If you do the first read with cin>>, you get "Hello" in your program, and left with
\n
World\n
If you then do the second read with getline, you get "" in your program, and left with
World\n
char userInput[256]; will be destroyed when readUserInput exits, so the pointer you return is invalid.
Use std::string instead.
Or allocate the variable dynamically, or pass an automatic variable as parameter.
userInput variable gets destroyed once it goes out of scope.
Local variables get stored on stack. Once the function execution completes, the variables get destroyed.
Either you need to use dynamically allocated char pointer(Stores on Heap) or std::string
you are using a pointer to a buffer (In stack) which is already out of scope.
Try this:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void _printOut(char * output)
{
cout << output << endl;
}
char * readUserInput()
{
//Allocate in Heap, instead of stack
char* userInput = new char[256];
cin >> userInput;
return userInput;
}
int main(int argc, char* argv[])
{
_printOut("Enter your name: ");
char * userName = readUserInput();
_printOut("Hello");
_printOut(userName);
system("pause");
return 0;
}
A better way would be to use std::string
Your problem here is a scoping issue:
char userInput[256]; defines a local variable that is only valid within its own scope (between ist set of {} brackets).
You essentially return a valid pointer that becomes invalid once you leaves the function, because it's freed.
You're violating a basic rule: never return pointers to local (non-static) variables.
To fix this, make your userInput static or return a new string (create a new string every call using new) or use copyable objects rather than pointers (like std::string).