Here is the code
#include "stdafx.h"
#include <string>
#include <clocale>
#include <stdio.h>
#include <cstdlib>
using namespace std;
int souls;
void userInput(char situation[20]) {
if (situation == "souls") {
scanf("%i", souls);
printf("%i", souls);
}
}
void main() {
setlocale(LC_CTYPE, "rus");
userInput("souls");
system("pause");
}
It brakes after I input something in my scanf() (trying to change a global int) via the console (int number for example) and drops me into an "unhandled exception"
Why is it so? I am using MS Visual Studio 2005.
In your code
scanf("%i", souls);
should be
scanf("%i", &souls);
^
scanf() needs a pointer to type as the argument to store the scanned value corresponding to the supplied format specifier.
That said, if (situation=="souls") is wrong, too. You cannot compare the contents of strings using the == operator. You need to use strcmp() for that.
Your code has several issues:
You cannot compare C strings this way: if (situation == "souls"): you are comparing the addresses of the char arrays, not their contents. You need to use strcmp (and include <cstring>) for this:
if (!strcmp(situation, "souls"))
The signature void userInput(char situation[20]) is confusing: the size 20 information is ignored and your are actually passing the address of a shorter string literal, this signature would be more appropriate:
void userInput(const char *situation)
You need to pass the address of the output variable to scanf and check the return value: scanf("%i", souls); invokes undefined behavior, it should be changed to:
if (scanf("%i", &souls) == 1) {
/* souls was assigned a value */
} else {
/* scanf failed to parse an integer */
}
The signature for main should not be void main(), it should be either:
int main()
or
int main(int argc, char *argv[])
Related
New to C++, more familiar with MATLAB and Arduino. I'm trying to create (read: modify someone else's code) a C++ function to send a character array over serial--it's interacting with a C library (rs232.h). I keep getting this error when initializing the default value for the mode--bits/baud/parity array in the function initialization. Not sure if I am trying to do something that is not supported, if so, I can split up the variables. Thanks in advance for any help.
IDE: Code::Blocks
Compiler: MinGW-g++/GCC 7.3
Errors:
error: could not convert '{'8', 'N', '1', 0}' from '<brace-enclosed initializer list>' to 'char*'
Code:
#include <stdlib.h>
#include <stdio.h>
#include <Windows.h>
#include "rs232.h"
#include <string> /* Probably unnecessary */
bool Write(char (&toWrite)[256], int portNum=3, int bdrate=9600, char mode[]={'8','N','1','\0'})
{
int i, cport_nr = portNum - 1;
if(RS232_OpenComport(cport_nr, bdrate, mode))
{
return false;
}
while(1)
{
RS232_cputs(cport_nr, toWrite);
printf("sent: %s\n", toWrite);
Sleep(1000);
i++;
i %= 2;
}
return true;
}
Put the default value at a separate line:
bool Write(char (&toWrite)[256], int portNum=3, int bdrate=9600, char *mode=NULL) {
char mode_default[] = {'8','N','1','\0'};
if (mode == NULL) mode = mode_default;
Reason:
You cannot use default values with C array parameters (which really decay to pointers here) – UnholySheep
I have a string function written in rtstring.c file which simply accept a string and return back the same string.
Then i have included this file in a body.cpp file and i want to pass string from
this file to c file.
How can I do this please help
My code
rtstring.c
#include <stdio.h>
char * rtstr(char * s)
{
return s;
}
body.cpp
#pragma once
#include "header.h"
#include "rtstring.c"
mystring::mystring(string str)
{
st=str;
}
string mystring::strreturn(string s1)
{
st=rtstr(s1);
return st;
}
header.h
#pragma once
class mystring
{
public:
mystring(string a);
string strreturn(string s1);
private:
string st;
}
main.cpp
#include <iostream>
using namespace std;
#include "header.h"
int main()
{
string rs,s="hi hello";
mystring str1(s);
rs=str.strreturn(s);
cout<<"string from c"<<rs;
return 0;
}
I an getting an error of return type mismatch and many associated error. Please help if there is anyway to deal with it. an example will be helpfull.
Thanks in advance
I an getting an error of return type mismatch
If you were to read the complete error message, I'm sure it would tell you that this is the problem:
char * rtstr(char * s)
// ^^^^^^
string mystring::strreturn(string s1)
// ^^^^^^
{
st=rtstr(s1);
// ^^
You are trying to pass a std::string into a function that instead expects char*.
To solve the problem, don't try to pass a std::string to functions that expect a char*. You'll probably find std::string::c_str() member function useful.
#include "rtstring.c"
Don't include source files. Especially don't include source files that were written in another language.
To call a function defined in another source file, just declare the function in the calling source and link the object file of the other source. Remember to set the language linkage when declaring cross-language functions. You'll find header files useful for including function declarations.
Your code is not much clear to me, but I understand your question.
So, accordingly, one of the simplest way is to write the string into a file using C programming and then reading the same file in your cpp program.
Your C program to write into a file:
#include <stdio.h>
#include <stdlib.h> /* For exit() function */
int main()
{
char s[1000];
FILE *fptr;
fptr = fopen("program.txt", "w");
if(fptr == NULL)
{
printf("Error!");
exit(1);
}
printf("Enter your string:\n");
gets(s);
fprintf(fptr,"%s", s);
fclose(fptr);
return 0;
}
Your cpp program something like this to read the same file.
#include<iostream.h>
#include<conio.h>
#include<fstream.h>
void main()
{
char c,fname[20] = 'program.txt';
clrscr();
ifstream in(fname);
if(!in)
{
cout<<"File Does not Exist";
getch();
return;
}
cout<<"\n\n";
while(in.eof()==0)
{
in.get(c);
cout<<c;
}
getch();
}
Another option could be to use pipe() function. More details.
I have figured it out a way which suits my requirement best.
I appreciate all your help thanks.
Changes i have done is as follows
body.cpp
`
string mystring::strreturn(string s1)
{
char *p,arr[9];
char *c=new char[s1.size()+1];
copy(s1.begin(),s1.end(),c);
c[s1.size()]='\0';
p=rtstr(c);
strcpy(arr,p);
st=arr;
return st;
}
`
please insert appropriate headers.
"using namespace std;" both in header.h and body.cpp
"#include" in header.h
First of all, you don't include source files. You should make rtstring.c it's own header, in which you declare the function rtstr.
Second, you're using a C++ compiler. If you want it to emulate C, you use using "C" { ... }. There are still fundamental differences between proper C and C++, so you're still using a C subset of C++, not actual C.
And finally, if you want to convert an std::string to a C string (char*), you can use its c_str() function.
When I use a dereference in a function as an argument, the preprocessor spits out an error.
I believe the * right before the parentheses causes ambiguity with the compiler.
Is there any way to get around this?
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
int main ()
{
char *in = NULL;
char *out = NULL;
getline(cin,in*);//error
out=system(in*);//error
printf(out);
return 0;
}
The errors are on marked lines.
Thank you!
Dereferencing in is written *in, not in*. (Also, even with that fixed, your program still won't work, as you're trying to dereference NULL, and the second argument to getline will have the wrong type. char* strings do not work the way you think they work.)
getline only works with C++ strings (not C-style strings). C++ strings can allocate memory as they go, in response to how much data is read.
There are other functions for reading into C strings, but you must pre-allocate the amount of memory you want, and also specify to the function how much memory you have allocated. In general there is no reason to do this, as the C++ string version is much simpler and less prone to error.
Also, avoid including C-style standard headers (i.e. ending in .h) and avoid using pointers. And system returns an int, not a string.
Example:
#include <iostream> // cin, cout
#include <string> // string
#include <cstdlib> // system
int main()
{
std::string s;
std::getline( std::cin, s );
int system_result = std::system( s.c_str() );
std::cout << system_result << "\n";
}
I am working with C++ in eclipse CDT and I am trying to convert string to uint64_t by using strtoull but everytime I get below error message -
..\src\HelloTest.cpp:39:42: error: strtoull was not declared in this scope
Below is my C++ example
#include <iostream>
#include <cstring>
#include <string>
using namespace std;
int main() {
string str = "1234567";
uint64_t hashing = strtoull(str, 0, 0);
cout << hashing << endl;
}
return 0;
}
Is there anything wrong I am doing?
Why your solution doesn't work has already been pointed out by others. But there hasn't been a good alternative suggested yet.
Try this for C++03 strtoull usage instead:
#include <string>
#include <cstdlib>
int main()
{
std::string str = "1234";
// Using NULL for second parameter makes the call easier,
// but reduces your chances to recover from error. Check
// the docs for details.
unsigned long long ul = std::strtoull( str.c_str(), NULL, 0 );
}
Or, since C++11, do it directly from std::string via stoull (which is just a wrapper for the above, but saves on one include and one function call in your code):
#include <string>
int main()
{
std::string str = "1234";
// See comment above.
unsigned long long ul = std::stoull( str, nullptr, 0 );
}
Never use char[] or pointers if you have a working alternative. The dark side of C++, they are. Quicker, easier, more seductive. If once you start down the dark path, forever will it dominate your destiny, consume you it will. ;-)
the structure for strtoull is: strtoull(const char *, char * *, int)
You have given it a std::string as pointed out by #juanchopanza
This is the solution I came up with is
#include <iostream>
#include <cstring>
#include <string>
#include <cstdlib>
using namespace std;
int main() {
char str[] = "1234567";
unsigned long long ul;
char* new_pos;
charDoublePointer = 0;
ul = strtoull(str, &new_pos, 0);
cout << ul << endl;
return 0;
}
The output I got was: 1234567
Straight from the eclipse console.
Also at the end of your program you have return 0 out of scope with an extra curly brace.
I am trying to include a function from another file inside a "main" file. I'm following this paradigm:
http://www.learncpp.com/cpp-tutorial/18-programs-with-multiple-files/
Here is my main file, digispark.cpp:
#include <iostream>
using namespace std;
int send(int argc, char **argv);
int main()
{
char* on;
*on = '1';
char* off;
*off = '0';
send(1,&on);
return 0;
}
And here is my send.cpp:
#include <stdio.h>
#include <iostream>
#include <string.h>
#if defined WIN
#include <lusb0_usb.h> // this is libusb, see http://libusb.sourceforge.net/
#else
#include <usb.h> // this is libusb, see http://libusb.sourceforge.net/
#endif
// I've simplified the contents of send for my debugging and your aid, but the
// complicated arguments are a part of the function that will eventually need
// to be here.
int send (int argc, char **argv)
{
std::cout << "Hello";
return 0;
}
I'm compiling on Ubuntu 12.10 using the g++ compiler like so:
g++ digispark.cpp send.cpp -o digispark
It compiles successfully.
However, when I run the program, "Hello" does not come up. Therefore I don't believe the function is being called at all. What am I doing wrong? Any help would be great! Thanks!
EDIT:
How I dealt with the issue:
int send(int argc, char **argv);
int main()
{
char* on[4];
on[0] = (char*)"send";
on[1] = (char*)"1";
char* off[4];
off[0] = (char*)"send";
off[1] = (char*)"0";
send(2,on);
return 0;
}
For those of you who were confused as to why I insisted doing this, as I said before, the send function was already built to accept the char** argv (or char* argv[]). My point was to try to mimic that in my main function.
It would have been much more difficult to rewrite the function that actually goes in the send function to take a different type of argument than just to send in what it wanted. Thanks everyone!
So if this helps anyone trying something similar feel free to use it!
Your problem is not the one you think it is. It's here:
char* on;
*on = '1';
You declared a char pointer, but did not initialize it. Then you dereferenced it. Bang, you're dead. This is what is known as Undefined Behavior. Once you invoke U.B., anything can happen. If you're lucky, it's a crash. But I guess you weren't lucky this time.
Look, if you want to start storing things in memory, you have to allocate that memory first. The best way, as hetepeperfan said, is to just use std::string and let that class take care of all the allocating/deallocating for you. But if for some reason you think you have to use C-style strings and pointers, then try this:
char on[128]; //or however much room you think you'll need. Don't know? Maybe you shoulda used std::string ...
*on = '1';
*(on+1) = '\0'; //if you're using C-strings, better null terminate.
char off[128];
*off = '0';
*(off+1) = '\0';
send(1,&on);
ok I think you try to do something like the following, I tried to make it a bit more in the Style of C++ and prevent the use of pointers since they should not be necessary in the code that you showed.
digispark.cpp
#include "send.h"
int main (int argc, char** argv){
string on = "1";
string off = "0";
send ( on );
send ( off );
return 0;
}
send.cpp
#include <iostream>
#include <string>
void send( const std::string& s) {
std::cout << s << std::endl;
}
send.h
void send(const std::string& s);