Just a simple problem here: I have a char** argv[] that holds all of my arguments...in one of these arguments, I get an integer proceeded by a %
For example:
bg %2
I really just want the integer....is there an easy way to get this?
This is for homework, so I am willing to do some more digging if anyone can prod me in the right direction.
Thanks
Here is a way to do it using c++ methods:
lets assume you have one of the char* in the list char** argv[]
std::string tempString(argv[the one with the %]);
int position = tempString.find_first_of('%');
int = atoi(tempString.substr(position, tempString.size()-position).c_str());
A quick explination, the first line converst the char* into a std::string, the second line gets the position of the %, the third line gets the sub-string of the number (assuming it ends at the end of the char*), converts it back to a char* and passes it through atoi to get the int.
Hope this helps.
Here is one way to do it using atoi:
for (int i = 0 ; i != argc ; i++) {
if (argv[i][0] == '%') {
int num = atoi(&argv[i][1]);
printf("Got a number: %d\n", num);
}
}
Related
I'm trying to use strncpy_s to characters from one word to an array (I cannot use strncpy in Visual Studio 2013 and I'm totally new to strncpy_s). I keep getting these errors whatever I do:
Error 1 error C2660: 'strncpy_s' : function does not take 3 arguments
Error 2 IntelliSense: no instance of overloaded function "strncpy_s"
matches the argument list argument types are: (char *, char, int)
The purpose of my code is:
If user inputs, for example, "HELLO" (that is, text = HELLO)
Then ->
Copy HELLO to first_array [0]
Copy ELLO to first_array [1]
Copy LLO to first_array [2]
Copy LO to first_array [3]
Copy O to first_array [4]
And here's my code:
int _tmain(int argc, _TCHAR* argv[])
{
char text[32];
cin >> text;
char* first_array[] = {""};
int n = strlen(text);
for (int i = 0; i < n; i++)
{
strncpy_s(first_array[i], text[i], n-i);
}
}
EDIT 1. Modified the code a bit more, now the program runs, but after inputing a text, it suddenly gives me the "example.exe stopped working" error.
int _tmain(int argc, _TCHAR* argv[])
{
char* text[32];
cin >> *text;
char* first_array[] = {""};
//int n = strlen(text);
int n = sizeof(text);
for (int i = 0; i < n; i++)
{
strncpy_s(first_array[i], n - i, text[i], 32);
}
Your code has several issues.
First of all, your call to strncpy_s does not follow the declaration of strncpy_s, which lists four parameters (if the first parameter is a char * as in your case):
errno_t strncpy_s(
char *strDest,
size_t numberOfElements,
const char *strSource,
size_t count
);
But much more importantly, you state that you would like to end up with multiple strings in an array first_array[], each holding a shorter version of the input string than the last. But the first_array[] you declared only holds one char * string, the one you initialized first_array[0] to, which is exactly one character long (the terminating null byte):
char* first_array[] = {""};
Even if you declared it to hold five char * (the initialization is not necessary as you copy the contents over anyway)...
char * first_array[5];
...you still haven't allocated memory space for each of the five char * strings. You just have five pointers pointing nowhere, and would have to allocate memory dynamically, depending on user input.
Because I haven't even talked about what happens if the user enters more than five characters, let alone 32...
At this point, even if I would post "working" code, it would teach you little. You are apparently following some kind of tutorial, or actually attempting to learn by trial & error. I think the right answer here would be:
Get a different tutorial. Even better, get a good book on C or a good book on C++ as online tutorials are notoriously lacking.
I have a char array and I want to find out the number of contents in it.
For example, my array is:
char myArray[10];
And after input it's content is:
ABC
Now I want to store in a variable 'size', the size of the area related to content. So, in this case:
size = 3
How do I find that?
A naive way of doing this would be to look for the null-terminating character \0, this is already implemented for you in the C-function strlen, so there are two ways of doing this:
int StringLength( const char* str, int maxLength )
{
for( int i = 0; i < maxLength; ++i )
{
if( str[i] == '\0' )
return i;
}
return -1;
}
Or you could just call strlen as follows:
int iLength = strlen( myArray );
However, as you have tagged this c++, the best way to do this would be to not deal with C-style character arrays and instead use the extremely useful std::string class.
strlen(myArray) is what you want.
Try this:
int len = strlen(myArray).
strlen is a part of stdlib.h library. Don't forget to declare it in your program.
defining array as char myArray[10]; will not always initialize it's content to zeros, so depending on how you fill it with ABC you either can or cannot find the corect lenght. In worst case regular strlen() will always report numbers >10, or even result in read access vialation. I try initialize it like char myArray[10] = {}; first
I'm trying to pass an unsigned int value via console argument to my program.
what have I tried yet:
first: check if argc is 2, otherwise error
if there is a second value I tried to convert this value with:
strtoul(argv[1], NULL, 0)
So when I pass "100", i get "1"
What am I doing wrong?
br
Sagi
€: passed a wrong argument to my function, found the mistake, thanks guys
It's a little hard to tell without seeing the actual code but you can use this as a baseline:
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char *argv[]) {
char *pCh;
unsigned long unlong = 42;
// Check enough arguments.
if (argc != 2) {
puts ("Not enough arguments");
return 1;
}
// Convert to ulong WITH CHECKING!
unlong = strtoul (argv[1], &pCh, 10);
// Ensure argument was okay.
if ((pCh == argv[1]) || (*pCh != '\0')) {
puts ("Invalid number");
return 1;
}
// Output converted argument and exit.
printf ("Argument was %ld\n", unlong);
return 0;
}
Transcript follows:
pax> ./testprog 314159
Argument was 314159
If that's not enough to help out, I suggest you post the shortest complete program that exhibits the problem, then we can tell you in excruciating detail what's wrong with it :-)
Your method should work. Alternatively, you can use stringstream:
std::string str(argv[1]);
unsigned long ul;
std::stringstream(str)>>ul;
I'm parsing a string that follows a predictable pattern:
1 character
an integer (one or more digits)
1 colon
a string, whose length came from #2
For example:
s5:stuff
I can see easily how to parse this with PCRE or the like, but I'd rather stick to plain string ops for the sake of speed.
I know I'll need to do it in 2 steps because I can't allocate the destination string until I know its length. My problem is gracefully getting the offset for the start of said string. Some code:
unsigned start = 0;
char type = serialized[start++]; // get the type tag
int len = 0;
char* dest = NULL;
char format[20];
//...
switch (type) {
//...
case 's':
// Figure out the length of the target string...
sscanf(serialized + start, "%d", &len);
// <code type='graceful'>
// increment start by the STRING LENGTH of whatever %d was
// </code>
// Don't forget to skip over the colon...
++start;
// Build a format string which accounts for length...
sprintf(format, "%%%ds", len);
// Finally, grab the target string...
sscanf(serialized + start, format, string);
break;
//...
}
That code is roughly taken from what I have (which isn't complete because of the issue at hand) but it should get the point across. Maybe I'm taking the wrong approach entirely. What's the most graceful way to do this? The solution can either C or C++ (and I'd actually like to see the competing methods if there are enough responses).
You can use the %n conversion specifier, which doesn't consume any input - instead, it expects an int * parameter, and writes the number of characters consumed from the input into it:
int consumed;
sscanf(serialized + start, "%d%n", &len, &consumed);
start += consumed;
(But don't forget to check that sscanf() returned > 0!)
Use the %n format specifier to write the number of characters read so far to an integer argument.
Here's a C++ solution, it could be better, and is hard-coded specifically to deal with your example input, but shouldn't require much modification to get working.
std::stringstream ss;
char type;
unsigned length;
char dummy;
std::string value;
ss << "s5:Helloxxxxxxxxxxx";
ss >> type;
ss >> length;
ss >> dummy;
ss.width(length);
ss >> value;
std::cout << value << std::endl;
Disclaimer:
I'm a noob at C++.
You can probably just use atoi which will ignore the colon.
e.g. len = atoi(serialized + start);
The only thing with atoi is that if it returns zero it could mean either the conversion failed, or that the length was truly zero. So it's not always the most appropriate function.
if you replace you colon with a space scanf will stop on it and you can get the size malloc the size then run another scanf to get the rest of the string`
int main (int argc, const char * argv[]) {
char foo[20];
char *test;
scanf("%s",foo); //"hello world"
printf("foo = %s\n", foo);//prints hello
//get size
test = malloc(sizeof(char)* 10);//replace 10 with your string size
scanf("%s", test);
printf("test = %s\n", test);//prints world
return 0;
}
`
Seems like the format is overspecified... (using a variable length field to specify the length of a variable length field).
If you're using GCC, I'd suggest
if (sscanf(serialized,"%c%d:%as",&type,&len,&dest)<3) return -1;
/* use type, dest; ignore len */
free(dest);
return 0;
I have a,
int main (int argc, char *argv[])
and one of the arguements im passing in is a char. It gives the error message in the title when i go to compile
How would i go about fixing this?
Regards
Paul
When you pass command line parameters, they are all passed as strings, regardless of what types they may represent. If you pass "10" on the command line, you are actually passing the character array
{ '1', '0', '\0' }
not the integer 10.
If the parameter you want consists of a single character, you can always just take the first character:
char timer_unit = argv[2][0];
If you only ever want the first character from the parameter the folowing will extract it from string:
char timer_unit = argv[2][0];
The issue is that argv[2] is a char* (C-string) not char.
You are probably not passing in what you think (though this should come from the command line). Please show the complete error message and code, but it looks like you need to deal with the second argument as char *argv[], instead of char argv[] -- that is, as a list of character arrays, as opposed to a single character array.
Everything stays strings when you pass them in to your program as arguments, even if they are single characters. For example, if your program was called "myprog" and you had this at the command line:
myprog arg1 53 c a "hey there!"
Then what you get in the program is the following:
printf("%d\n", argc);
for(int i = 0; i < argc; i++)
{
printf("%s\n", argv[0]);
}
The output of that would be:
6
myprog
arg1
53
c
a
hey there!
The point being that everything on the command line turns into null-terminated strings, even single characters. If you wanted to get the char 'c' from the command line, you'd need to do this:
char value = argv[3][0];
not
char value = argv[3]; // Error!
Even the value of "53" doesn't turn into an int. you can't do:
int number = argv[2]; // Error!
argv[2] is { '5', '2', '\0' }. You have to do this:
int number = atoi(argv[2]); // Converts from a string to an int
I hope this is clear.
Edit: btw, everything above is just as valid for C (hence the printf statements). It works EXACTLY the same in C++.