Sunday, July 12, 2009

How can I iterate a character/string in C?

I want to iterate some like \". I tried





char test;


test = "\"";


printf("%c", test);





What should I be doing?

How can I iterate a character/string in C?
I believe you've confused the term "iterate" with the term "escape". You want to *escape* the double-quote character, to use it as a literal character, correct?





You need to use single quotes to delimit a char literal;





test = '\"';





A literal value delimited with double-quotes evaluates to a char* type, rather than just a char.





The term iterate means to traverse an array or collection, usually from beginning to end, nearly always involving a loop construct (such as for or while.)
Reply:I'm not sure what you mean by "iterate" here. It seems like you may mean "imbed a string constant in another string constant". This is usually done when you're producing text to be read in by another program. To do that you need two sets of double-quotes:





char* test = "\"This is the interior string\" ";


printf( "%s", test );





Hope that helps.
Reply:C is a very low level language. You need a language such as C++ that has a string class and operator overloading if you want to use a construct such as your example using the * operator to multiply.


In C we generally store character literals in integers as such:





int test = '"'; /* Character literals are enclosed in single quotes so there's no reason to escape the double quote */





You could do a simple C program as such:





#include %26lt;stdio.h%26gt;





int quote = '"';





main()


{


int c;


for(c=0; c++; c %26lt; 3){


putchar(quote);


}


putchar('\n');


exit(0);


}





There are about a zillion ways to do what you want, but no real operator overloading, etc. in C. Perhaps it's not the language you're looking for?
Reply:Add one more escape sequence \ before \


like "\\". Hope it works


No comments:

Post a Comment