what is string strName<>? - string

I have seen code like this:
struct failed_login_res {
string errorMsg<>;
unsigned int error;
};
What does the <> at the end mean? How is it different from normal declaration like string errorMsg?
Correction: this is for RPC stub, not C++ and I can confirm that it does compile. The question is then still valid.

From a quick googling, I came across this PDF.
Section 6.9 is as follows:
Strings: C has no built-in string type, but instead uses the null-terminated “char *” convention. In XDR language, strings are declared using the “string” keyword, and compiled into “char *”s in the output header file. The maximum size contained in the angle brackets specifies the maximum number of characters allowed in the strings (not counting the NULL character). The maximum size may be left off, indicating a string of arbitrary length.
Examples:
string name<32>; --> char *name;
string longname<>; --> char *longname;

Related

C++ return length of string including contained null terminator bytes

The methods for getting the length of a string in C++ all seem to count up to a null terminating byte, then they either include it in the length or not and then return the length up to then. Well lets say I have a String like this:
'h','e','l','l','o','\0','t','h','e','r','e'
Now if you call length on this string you will get 5 as the length. I need a call on this string that will return 11. Is this possible?
A C++ string is by definition also a C-string, so it will always be null terminated. For this particular problem, I recommend using std::vector< char >

Problems assigning char string to char array

I have already read all prior answers regarding my problem. However, I'm not a very bright coder to am unable to grasp it. Could someone please look into my problem.
I am trying to write a CSV file using entries from a 2D array. string.h has already been included in main().
void create_marks_csv(int rout[][20],float p[][20],float c[][20],int n)
{
system("cls");
char str1[100],str2[100],str3[100];
printf("\nEnter filename for routing matrix: ");
gets(str1);
printf("\n Creating %s.csv file",str1);
FILE *fp;
int i,j;
str1=strcat(str1,".csv");
str1=strcat("C:\\Users\\Neil\\Documents\\Trust CSV Logs\\",str1) ;
fp=fopen(str1,"w+");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
if(i==j)
fprintf(fp,"X");
else
fprintf(fp,"%d",rout[i][j]);
}
fprintf(fp,"\n");
}
fclose(fp);
printf("\nFile created: %s",str1);
system("cls");
}
The warnings and errors are as follows:
5 20 C:\Users\Neil\Documents\main.c [Warning] extra tokens at end of #include directive [enabled by default]
C:\Users\Neil\Documents\main.c In function 'create_marks_csv':
168 6 C:\Users\Neil\Documents\main.c [Error] incompatible types when assigning to type 'char[100]' from type 'char *'
169 6 C:\Users\Neil\Documents\main.c [Error] incompatible types when assigning to type 'char[100]' from type 'char *'
28 C:\Users\Neil\Documents\Makefile.win recipe for target 'main.o' failed
Every time you write str1 =, you are telling the compiler to change str1 so that it points to whatever location in memory is found on the right-hand side of the = sign. But you declared char str1[100], which means that str1, interpreted as a pointer, can only point to the start of the block of 100 characters at the location where this declaration allocated them. So it makes no sense to write str1 =.
Passing a C string constant as the first argument of strcat is likely to be a disaster, although the compiler seems not to mind. The first argument of strcat should be a character buffer big enough to hold the results of the concatenation. In order to concatenate something onto the end of a constant string, you can allocate a buffer big enough, then copy the constant string to it, then call strcat.
In general you can probably do whatever you need to do without using the return value of strcat, that is, no need to ever write strcat on the right-hand side of =.
It is advisable to use fgets instead of gets because then you can protect against the possibility that you will get too much input to fit in your allocated character buffer. If you allocate 100 characters in your largest buffer, you can only afford to accept 95 characters minus the length of the string "C:\\Users\\Neil\\Documents\\Trust CSV Logs\\". (The other 5 characters are required to hold the string ".csv" and the terminating null character).
I saw also that you declare str2 and str3 but I didn't see where you used either of them. It looks like you don't need both of them, but you might find it convenient to use str2 as the buffer for your last concatenation of strings.

Go - Comparing strings/byte slices input by the user

I am getting input from the user, however when I try to compare it later on to a string literal it does not work. That is just a test though.
I would like to set it up so that when a blank line is entered (just hitting the enter/return key) the program exits. I don't understand why the strings are not comparing because when I print it, it comes out identical.
in := bufio.NewReader(os.Stdin);
input, err := in.ReadBytes('\n');
if err != nil {
fmt.Println("Error: ", err)
}
if string(input) == "example" {
os.Exit(0)
}
string vs []byte
string definition:
string is the set of all strings of 8-bit bytes, conventionally but not necessarily representing UTF-8-encoded text. A string may be empty, but not nil. Values of string type are immutable.
byte definition:
byte is an alias for uint8 and is equivalent to uint8 in all ways. It is used, by convention, to distinguish byte values from 8-bit unsigned integer values.
What does it mean?
[]byte is a byte slice. slice can be empty.
string elements are unicode characters, which can have more then 1 byte.
string elements keep a meaning of data (encoding), []bytes not.
equality operator is defined for string type but not for slice type.
As you see they are two different types with different properties.
There is a great blog post explaining different string related types [1]
Regards the issue you have in your code snippet.
Bear in mind that in.ReadBytes(char) returns a byte slice with char inclusively. So in your code input ends with '\n'. If you want your code to work in desired way then try this:
if string(input) == "example\n" { // or "example\r\n" when on windows
os.Exit(0)
}
Also make sure that your terminal code page is the same as your .go source file. Be aware about different end-line styles (Windows uses "\r\n"), Standard go compiler uses utf8 internally.
[1] Comparison of Go data types for string processing.

Number of characters in pointer

This is very simple but I forgot since the last time i did it was two months ago. I want to know how you find the number of characters (letters) in a string pointer. I tried to use sizeof() and strlen() but they return the wrong value. For example, when insert="-dh o output -i input", the sizeof() function returns 210. I would greatly appreciate your help. My function:
int find(char* insert, char* check)
{
}
strlen() should give the right answer (the length of the string) for a null-terminated string. sizeof is an operator, which in this case will return the number of bytes required to represent the char pointer.

Basics of Strings

Ok, i've always kind of known that computers treat strings as a series of numbers under the covers, but i never really looked at the details of how it works. What sort of magic is going on in the average compiler/processor when we do, for instance, the following?
string myString = "foo";
myString += "bar";
print(myString) //replace with printing function of your choice
The answer is completely dependent on the language in question. But C is usually a good language to kind of see how things happen behind the scenes.
In C:
In C strings are array of char with a 0 at the end:
char str[1024];
strcpy(str, "hello ");
strcpy(str, "world!");
Behind the scenes str[0] == 'h' (which has an int value), str[1] == 'e', ...
str[11] == '!', str[12] == '\0';
A char is simply a number which can contain one of 256 values. Each character has a numeric value.
In C++:
strings are supported in the same way as C but you also have a string type which is part of STL.
string literals are part of static storage and cannot be changed directly unless you want undefined behavior.
It's implementation dependent how the string type actually works behind the scenes, but the string objects themselves are mutable.
In C#:
strings are immutable. Which means you can't directly change a string once it's created. When you do += what happen is a new string gets created and your string now references that new string.
The implementation varies between language and compiler of course, but typically for C it's something like the following. Note that strings are essentially syntactical sugar for char arrays (char[]) in C.
1.
string myString = "foo";
Allocate 3 bytes of memory for the array and set the value of the 1st byte to 'f' (its ASCII code rather), the 2nd byte to 'o', the 2rd byte to 'o'.
2.
foo += "bar";
Read existing string (char array) from memory pointed to by foo.
Allocate 6 bytes of memory, fill the first 3 bytes with the read contents of foo, and the next 3 bytes with b, a, and r.
3.
print(foo)
Read the string foo now points to from memory, and print it to the screen.
This is a pretty rough overview, but hopefully should give you the general idea.
Side note: In some languages/compuilers, char != byte - for example, C#, where strings are stored in Unicode format by default, and notably the length of the string is also stored in memory. C++ typically uses null-terminated strings, which solves the problem in another way, though it means determining its length is O(n) rather than O(1).
Its very language dependent. However, in most cases strings are immutable, so doing that is going to allocate a new string and release the old one's memory.
I'm assuming a typo in your sample and that there is only one variable called either foo or myString, not two variables?
I'd say that it'll depend a lot on what compiler you're using. In .Net strings are immutable so when you add "bar" you're not actually adding it but rather creating a new string containing "foobar" and telling it to put that in your variable.
In other languages it will work differently.

Resources