sprintf (convert int to char[]) - string

In my program I try to convert a int to a char[20];
I try to do this in the following way:
char str[20];
sprintf(str, "%d", timer);
in which timer is the int.
But when I build this code, I get the following warnings.
Type implicit declaration of function 'sprintf' [-Wimplicit-function-declaration]
incompatible implicit declaration of built-in function 'sprintf' [enabled by default]
what does that mean?
note:( I have included string.h and stdlib.h).
great, I added stdio.h to my code and now the warnings disappeared only to give me a even harder error.
undefined reference to `_sbrk'

You have to #include <stdio.h> to use sprintf()

you want to make sure you also add reference to stdio.h see this ref

You probably need to put sprintf(str, "%d", timer) inside a function (not on the global part of the source code).
Something like:
#include <stdlib.h>
char str[20];
// SPOT #1
int f() {
sprintf(str, "%d", timer); // this won't work if placed on SPOT #1
}

Related

GCC interprets uint8_t and uint16_t as signed? [duplicate]

This question already has answers here:
Format specifiers for uint8_t, uint16_t, ...?
(7 answers)
Closed 3 years ago.
My test code:
#include <cstdint>
#include <cstdio>
int main() {
const constexpr uint8_t x = 64;
printf("%u", x);
}
Here is how I compiled with GCC 8.2:
g++ -Wall test_format.cpp -o test_format -O3 -std=c++17 -Wformat-signedness
And here is GCC's output:
test_format.cpp: In function ‘int main()’:
test_format.cpp:6:9: warning: format ‘%u’ expects argument of type ‘unsigned int’, but argument 2 has type ‘int’ [-Wformat=]
printf("%u", x);
^~~~
Tho, if I try to print an uint32_t, it has no error/warning.
I wonder why GCC expects uint8_t to be signed int.
Thanks.
Default argument promotions are applied to operands of a variadic function. Under these, an expression of type unsigned char is promoted to int.
In C and C++ types narrower than int are always promoted to int. See Why must a short be converted to an int before arithmetic operations in C and C++?
And inside variadic functions default promotion also applies, which means you can't pass types narrower than int to vararg functions. So uint8_t must be printed with %d, not %u. But anyway you're printing it the wrong way. The correct way is to use PRIu8
printf("%" PRIu8 "\n", x);
Format specifiers for uint8_t, uint16_t, ...?
printing the uint8_t
Why is the format specifier for uint8_t and uint16_t the same (%u)?
How do I print uint32_t and uint16_t variables value?
To print a uint8_t variable with printf(), you should do something like the following:
#include <cinttypes>
#include <cstdio>
int print_u8(std::uint8_t x) {
return std::printf("%" PRIu8 "\n", x);
}
The <cinttypes> header includes printf and scanf format specifiers for all the <cstdint> types (and explicitly includes that header) that should be used for maximum portability.

I am not able to link 2 .cpp files with a header in visual studio

I have a file p2.cpp and 2d.cpp which I'm trying to link with 2d.h.
I have included 2d.h in both .cpp files and I'm getting an error:
2d.obj : error LNK2005: "float (* v)[3]" (?v##3PAY02MA) already defined in p2.obj
1: fatal error LNK1169: one or more multiply defined symbols found.
What should I do?
I have a file p2.cpp and 2d.cpp which I'm trying to link with 2d.h. I
have included 2d.h in both .cpp files and I'm getting an error:
Each symbol may only be defined in a program once (refer One definition rule). I'm not sure what you're header file looks like, but typically this means something to the effect of defining something in you're header file that is included in more than one compilation unit. You could "extern" it in you're header, and ensure that it is defined in a separate compilation unite.
From the compiler error it looks like you've define an array of pointers to functions in your header file. Extern this and provide a single definition in a source file.
This code effectively causes the problem:
//--- Def.h
#ifndef DEF_H
#define DEF_H
float foo();
/*extern */float (*floatFunctionArray[3])();
#endif /* DEF_H */
//--- Def.cpp
#include "Def.h"
float foo()
{
return 0;
}
float (*floatFunctionArray[3])() =
{
foo, foo, foo
};
//--- main.cpp
#include "Def.h"
int
main(int argc, char** argv)
{
return 0;
}
Adding the commented out "extern" solves the issue.

Enabling string conversion functions in MinGW

this code:
#include <iostream>
#include <string>
int main()
{
std::string s = "52123210";
int derp = std::stoi(s, 0, 10);
std::to_string(derp);
return 0;
}
with this error:
test.cpp:10:2: error: 'stoi' is not a member of 'std'
test.cpp:11:2: error: 'to_string' is not a member of 'std'
tried this:
http://tehsausage.com/mingw-to-string
(not work)
Update my MingW from 4.6.1 to 4.8.1
(not work)
possible bug:
http://gcc.gnu.org/bugzilla/show_bug.cgi?id=37522
(beyond of my knowledge to apply anything, I don't dare to touch the compiler's code)
**Also not work with "using namespace std" but produced 'stoi' and 'to_string' not declared
error instead.
This is a result of a non-standard declaration of vswprintf on Windows. The GNU Standard Library defines _GLIBCXX_HAVE_BROKEN_VSWPRINTF on this platform, which in turn disables the conversion functions you're attempting to use.
https://stackoverflow.com/a/8543540/2684539 proposes a hack/work around.

Confused about all the different string types and how to use them properly in Visual C++

Years ago, I used to do some basic programming in C. Now I am attempting to relearn what I have forgotten as well as learn Visual C++. I am confused though by all the string options and now the extra layer of trying to make my programs Unicode compatible. I have been reading Beginning Visual C++ 2010 as well as online reading to learn this information.
As an exercise I am writing a very basic program that asks a user to input some text and then display that text in the form of a messagebox. The program works, but my way of getting it to work was more through guesswork and looking at other examples than truly understanding why I need to convert the various strings into different types.
The code is:
#include "stdafx.h"
#include <iostream>
#include <string>
#include "Windows.h"
using std::wcin;
using std::wcout;
using std::wstring;
int _tmain(int argc, _TCHAR* argv[])
{
wstring myInput;
wcout << "Enter a string: ";
getline(wcin, myInput);
MessageBoxW(NULL, myInput.c_str(), _T("Test MessageBox"), 64);
return 0;
}
The MessageBox syntax is:
int WINAPI MessageBox(
__in_opt HWND hWnd,
__in_opt LPCTSTR lpText,
__in_opt LPCTSTR lpCaption,
__in UINT uType
);
On the other hand, if I just use the command line argument as the text of the messagebox, I do not need to convert the string at all and I am not sure why.
#include "stdafx.h"
#include <iostream>
#include <string>
#include "Windows.h"
using std::wcout;
int _tmain(int argc, _TCHAR* argv[])
{
MessageBoxW(NULL, argv[1], _T("Test MessageBox"), 64);
return 0;
}
My confusion is:
Why do I need to use the c_str() for argument 2 to MessageBoxW and why do I need to use the _T() macro (?) in argument 3?
Why did the program work in the second code example without doing some sort of conversion?
What exactly does LPCTSTR mean? I see another variant in MSDN functions called LPTSTR.
Thanks!
1) .c_str() is a standard C++ method to convert from C++ strings to C strings. _tmain, _T('x'), _T("text") and _TCHAR are (somewhat ugly) Microsoft macros that make your program compile either in unicode or non-unicode mode. There's a global setting in the project options that set some macros to configure your project in one of these two modes.
If you are in non-unicode mode (referred to as ANSI mode in MS's documentation) the macros expand to:
main, 'x', "text", char
If you are in unicode mode, the macros expand to
wmain, L'x', L"text", wchar_t
2) and 3) Windows headers are full of typedefs and macros like that. Sometimes they make code more obscure thant it needs to be. In general, LP means pointer (long pointer, i guess, but it's been a while since we needed to distinguish between near and far pointers), C means "const", T means that it will be either char or wchar_t depending on project settings and STR is obviously "string". After all, it's a plain C type, that's why you can pass C strings to them without conversion.
The MessageBoxW function is expecting a C-style wide-character string (WCHAR ). The macro _L() alters your string so that it's Unicode compatible (WCHAR instead of char*).
argv[] doesn't do objects, so you're already getting a WCHAR pointer out of it.
LPCTSTR is basically a WINAPI typedef for const char * or const WCHAR*, depending on whether you are building as UNICODE. Also see this post: LPCSTR, LPCTSTR and LPTSTR
In short, your main function is being passed WCHAR* strings and MessageBoxW expects WCHAR* strings.

How to use set_intersection with std::set in VC++?

I'm trying to compile VC6 project with VC10...
I obtain an error C2678 with set_intersection: I wrote some example to understand. Can anybody explain how to compile this snippets ?
#include <vector>
#include <algorithm>
#include <iostream>
#include <set>
#include <string>
int main( )
{
using namespace std;
typedef set<string> MyType;
MyType in1, in2, out;
MyType::iterator out_iter(out.begin());
set_intersection(in1.begin(),in1.end(), in2.begin(), in2.end(), out_iter);
}
The output :
c:\program files\microsoft visual\studio 10.0\vc\include\algorithm(4494): error C2678: '=' binary : no operator defined which takes a left-hand operand of type 'const std::basic_string<_Elem,_Traits,_Ax>' (or there is no acceptable conversion)
If I use a std::vector instead of std::set the compilation succeeded.
acceptable)
Try
set_intersection(in1.begin(),in1.end(), in2.begin(), in2.end(), inserter(out, out.begin()) );
This is because set_intersection wants to write to the output iterator, which causes the output container to grow in size. However this couldn't be done with just an iterator alone (it could be used to overwrite existing elements but not grow in size)
Edit: fixed the typo. Use inserter for adding to a set. A back_inserter only works for vectors and such.
Edit 2: fixed another typo. STL inserter requires a second argument which is a hint iterator to the likely insert position. Thanks chepseskaf.

Resources