Converting int to string without printing [duplicate] - string

This question already has answers here:
How can I convert an int to a string in C?
(10 answers)
Closed 8 years ago.
I want to convert an int to a string without printing anything on my screen. For now I used sprintf, but this also printed the int to my screen.
Also itoa is not supported by my compiler so I can't use that either.

I assume You use ANSI C.
You cannot use itoa because it's not a standard function.
sprintf or snprintf is dedicated to that.
Since You do not want to use sprintf, make your own itoa instead:
#include <stdio.h>
char* itoa(int i, char b[]){
char const digit[] = "0123456789";
char* p = b;
if(i<0){
*p++ = '-';
i *= -1;
}
int shifter = i;
do{ //Move to where representation ends
++p;
shifter = shifter/10;
}while(shifter);
*p = '\0';
do{ //Move back, inserting digits as u go
*--p = digit[i%10];
i = i/10;
}while(i);
return b;
}
original answer: here

Related

C function to remove instances of one char from a string

I did it right but it only works if the base string is one word:
#include <stdio.h>
void withoutString(char *new, char *base, char removee){
while(*base){
if(*base!=removee){
*new++=*base;}
base++;
}
*new='\0';
}
int main()
{
char b[16],n[16],r;
printf("Please enter string: ");
scanf(" %s", b);
printf("Which character do you want to remove? \n");
scanf(" %c",&r);
withoutString(n, b, r);
printf(" The new string is %s", n);
return 0;
}
How do I make it work for more words?
Read and understand the documentation of scanf. Good sources for documentation on the C standard functions are the C standard itself and POSIX.
You will then notice that scanf is not the best function to read a whole line, so look for fgets next.

Convert String to hex little endian format in C++

I have a string 2290348
I need it to display as ACF22200 (little endian)
Because the input 2290348 is passed in via a form in textbox, I have tried to read it as string (eg. this->textBox1->Text) and convert it to int (eg. Convert::ToInt32(this->textBox1->Text)).
afterwhich, i converted it to hex via ToString("x") which i manage to get 22F2AC
I appended 00 to 22F2AC and gotten 0022F2AC still as string
now i'm stuck in converting 0022F2AC to ACF22200
While still an int, you could use e.g. htonl to convert it to "network" byte order.
#include <winsock2.h>
int main()
{
unsigned int x = 0x22F2AC;
printf("x = 0x%08x\n", x);
printf("htonl(x) = 0x%08x\n", htonl(x));
return 0;
}
The program above prints:
x = 0x0022f2ac
htonl(x) = 0xacf22200

Loop to keep adding spaces in string?

I have the following code:
sHexPic = string_to_hex(sPic);
sHexPic.insert(sHexPic.begin() + 2,' ');
sHexPic.insert(2," ");
I would like to know how I can put this into a counted loop and add a space after every 2nd character. So far all this does is make this string "35498700" into "35 498700", which in the end I want the final result to be something like "35 49 87 00".
I assume you would have to get the length of the string and the amount of characters in it.
I am trying to achieve this in c++/cli.
Thanks.
Here's how it would be done in C++, using a string :) (I'm using C libraries cuz I'm more familiar with C)
#include <stdio.h>
#include <string>
using namespace std;
int main()
(
string X;
int i;
int y;
X = 35498700;
y= X.size();
for(i=2;i<y;i+=2)
{
X.insert(i," ");
y=x.size(); //To update size of x
i++; //To skip the inserted space
}
printf("%s",X);
return 0;
}
Have fun :)
That would "probably" work. If it didn't then please mention so :)

Parsing a string with varying number of whitespace characters in C

I'm pretty new to C, and trying to write a function that will parse a string such as:
"This (5 spaces here) is (1 space
here) a (2 spaces here) string."
The function header would have a pointer to the string passed in such as:
bool Class::Parse( unsigned char* string )
In the end I'd like to parse each word regardless of the number of spaces between words, and store the words in a dynamic array.
Forgive the silly questions...
But what would be the most efficient way to do this if I am iterating over each character? Is that how strings are stored? So if I was to start iterating with:
while ( (*string) != '\0' ) {
--print *string here--
}
Would that be printing out
T
h
i... etc?
Thank you very much for any help you can provide.
from http://www.cplusplus.com/reference/clibrary/cstring/strtok/
/* strtok example */
#include <stdio.h>
#include <string.h>
int main ()
{
char str[] ="- This, a sample string.";
char * pch;
printf ("Splitting string \"%s\" into tokens:\n",str);
pch = strtok (str," ,.-"); /* split the string on these delimiters into "tokens" */
while (pch != NULL)
{
printf ("%s\n",pch);
pch = strtok (NULL, " ,.-"); /* split the string on these delimiters into "tokens" */
}
return 0;
}
Splitting string "- This, a sample string." into tokens:
This
a
sample
string
First of all, C does not have classes, so in a C program you would probably define your function with a prototype more like one of the following:
char ** my_prog_parse(char * string) {
/* (returns a malloc'd array of pointers into the original string, which has had
* \0 added throughout ) */
char ** my_prog_parse(const char * string) {
/* (returns a malloc'd NULL-terminated array of pointers to malloc'd strings) */
void my_prog_parse(const char * string, char buf, size_t bufsiz,
char ** strings, size_t nstrings)
/* builds a NULL-terminated array of pointers into buf, all memory
provided by caller) */
However, it is perfectly possible to use C-style strings in C++...
You could write your loop as
while (*string) { ... ; string++; }
and it will compile to exactly the same assembler on a modern optimizing compiler. yes, that is a correct way to iterate through a C-style string.
Take a look at the functions strtok, strchr, strstr, and strspn... one of them may help you build a solution.
I wouldn't do any non-trivial parsing in C, it's too laborious, the language is not suitable for that. But if you mean C++, and it looks like you do, since you wrote Class::Parse, then writing recursive descent parsers is pretty easy, and you don't need to reinvent the wheel. You can take Spirit for example, or AXE, if you compiler supports C++0x. For example, your parser in AXE can be written in few lines:
// assuming you have 0-terminated string
bool Class::Parse(const char* str)
{
auto space = r_lit(' ');
auto string_rule = "This" & r_many(space, 5) & space & 'a' & r_many(space, 2)
& "string" & r_end();
return string_rule(str, str + strlen(str)).matched;
}

C++/CLI String Conversions

I found this really nice piece of code that converts a string to a System:String^ as in:
System::String^ rtn = gcnew String(move.c_str()); // 'move' here is the string
I'm passing rtn back to a C# program. Anyways, inside the function where this code exists, I'm passing in a System::String^. I also found some code to convert a System:String^ to a string using the following code:
pin_ptr<const wchar_t> wch = PtrToStringChars(cmd); // 'cmd' here is the System:String
size_t convertedChars = 0;
size_t sizeInBytes = ((cmd->Length + 1) * 2);
errno_t err = 0;
char *ch = (char *)malloc(sizeInBytes);
err = wcstombs_s(&convertedChars,ch, sizeInBytes,wch, sizeInBytes);
Now I can use 'ch' as a string.
This, however, seems to be alot more work than converting the other way using the gcnew. So, at last my question is, is there something out there that will convert a System::String^ to string using a similar fashion as with the gcnew way?
Use VC++'s marshaling library: Overview of Marshaling in C++
#include <msclr/marshal_cppstd.h>
// given System::String^ mstr
std::string nstr = msclr::interop::marshal_as<std::string>(mstr);
this could be useful:
wchar_t *str = "Hi StackOverflow"; //native
String^ mstr= Marshal::PtrToStringAnsi((IntPtr)str); // native to safe managed
wchar_t* A=( wchar_t* )Marshal::StringToHGlobalAnsi(mstr).ToPointer(); // return back to native
don't forget using namespace System::Runtime::InteropServices;

Resources