C++: Mixing cout with sprintf and strings

I'm writing a C++ program, writing to sysout using cout. Because iostream's formatting codes are so completely bizarre and incomprehensible to me, I want to use sprintf() to build the output string, and cout to print it. And I'm having the worst time of it, probably because of not completely understanding const.
char buffer[81]; // +sprintf char[] buffer.+ *How is a programmer meant to post code fragments to this forum when brackets, pluses, underscores, and asterisks are interpreted as markup?????*+
string s = "%-" + itos(longest) + "s "; // +itos() converts int to string. it works correctly.+
char * c = s.c_str(); // +convert format string to a char*, which sprintf requires+
* ERROR: invalid conversion from "const char *" to "char *" *
sprintf(buffer, c, (n < wordvec.size()) ? wordvec[n] : ""); //
* WARNING: cannot pass objects of non-POD type ... call will abort at runtime
cout << buffer;
Can anyone advise me on what is the right way to do this, without having to learn iostream manipulators and other grossness? (s)printf is SO easy....
Thanks,
Chap

Chap Harrison wrote:
char buffer[81]; // +sprintf char[] buffer.+ *How is a programmer meant to post code fragments to this forum when brackets, pluses, underscores, and asterisks are interpreted as markup?????*+
string s = "%-" + itos(longest) + "s "; // +itos() converts int to string. it works correctly.+
char * c = s.c_str(); // +convert format string to a char*, which sprintf requires+
* ERROR: invalid conversion from "const char *" to "char *" *
sprintf(buffer, c, (n < wordvec.size()) ? wordvec[n] : ""); //
* WARNING: cannot pass objects of non-POD type ... call will abort at runtime
cout << buffer;
</div>
Wordvec appears to be a std::string. You will have to convert it before you can print it. As for the const problem, there isn't much I can tell you. c_str() returns a const char *. You can't/shouldn't cast that into a char *. In fact, you don't even need to do that at all.
sprintf(buffer, "%-*s", longest, n < wordvec.size()) ? wordvec[n].c_str() : ");

Similar Messages

  • Downloaded LR 5 on a second computer, got  it mixed up with CC and now "Desktop is deactivated" and...please renew...BUT I CAN'T FIND A DIALOG BOX IN WHICH TO PUT MY SERIAL NUMBER?

    I downloaded Lightroom 5 on a second computer (desktop), but during installation I seen to have it got mixed up with CC which I don't want to engage in now. Now "Desktop has been deactivated..." and would I please renew membership... BUT I CAN'T FIND A DIALOG BOX IN WHICH TO PUT MY SERIAL NUMBER.

    if you don't have/want a cc subscription on your computer, uninstall the cc app and then use the cleaner -  Use the CC Cleaner Tool to solve installation problems | CC, CS3-CS6
    if necessary reinstall lightroom and license with your serial number -
    Downloads available:
    Suites and Programs:  CC 2014 | CC | CS6 | CS5.5 | CS5 | CS4 | CS3
    Acrobat:  XI, X | 9,8 | 9 standard
    Premiere Elements:  13 | 12 | 11, 10 | 9, 8, 7
    Photoshop Elements:  13 |12 | 11, 10 | 9,8,7
    Lightroom:  5.7.1| 5 | 4 | 3
    Captivate:  8 | 7 | 6 | 5
    Contribute:  CS5 | CS4, CS3
    Download and installation help for Adobe links
    Download and installation help for Prodesigntools links are listed on most linked pages.  They are critical; especially steps 1, 2 and 3.  If you click a link that does not have those steps listed, open a second window using the Lightroom 3 link to see those 'Important Instructions'.

  • Core dump with stlport4 and string pointers

    Hello,
    I am porting from SGI Irix to Sun Solaris, using OS 8 and Sun Studio 8. The program we are porting is very very large. We've compiled all code, but now are getting core dumps on several of the executables. We have traced one of the core dumps to a function that deals with string manipulation/string pointers. We wrote a very simple test program that re-produces the problem.
    #include <string>
    #include <iostream>
    void test(char* m)
    std::cout << m << " in test before";
    m[0] = 'z';
    std::cout << m << " in test after";
    void main(void)
    char* temp = new char[10];
    temp = "abcd";
    std::cout << temp << " before test";
    test(temp);
    std::cout << temp << " after test";
    We get the following output:
    abcd before test
    abcd in test before
    Segmentation fault (core dumped)
    The code compiles and runs fine on the SGI Irix system. What am I doing wrong?
    Thanks,
    Bob

    1) The signature of "main" is wrong. It must be 'int
    main(int, char **)'Not quite. The signatures
    int main()
    int main(void)
    are also allowed. (C++ standard, section 3.6.1 Main function)
    A "void" return type on main is not standard, but Sun C++ allows it with a warning. Such a version of main does not return a predictable value to the program that invoked it (usually the shell).
    It seems as if the intent of the program is to
    allocate a new string with the contents "abcd".
    Instead, you allocate a buffer, and then overwrite the
    pointer to that buffer with a pointer to a string
    constant, to which you then attempt to write.Right. By default, the C++ compiler allocates string literals to read-only memory, to catch mistakes like this. The compiler has an option to store literal strings in read-write memory, but we recommend against using the option, since you should not ever want to modify a literal string.
    I am curious why the compiler doesn't complain about
    the assignment in main - to my eyes it looks like it
    should be complaining that you are assigning a const
    char * to a char *The compiler emits a warning about the assignment.
    Such code is allowed but deprecated in the C++ standard, because of the deprecated conversion of "array of const char" to char* (section 4.2 Array-to-pointer conversion).

  • Creating a LabVIEW Shared DLL for use with C# and Strings?

    Hi All,
    I am trying to create a prototype for a LabVIEW Shared DLL that all the VI does is take in a string and return an upper cased string. Needless to say the DLL builds fine but when I try calling the shared DLL from C# the .NET application recieves an exception about "Ansi char arrays can not be marshaled as byref or as an unmanaged-to-managed parameter". Does anyone have an example of how to pass a string to a VI and return a string or an example of a better way of accomplishing this.
    We are using labVIEW 7.1 on Windows 2000.
    I am in quite a bit of a hurry to prove that this type of a LabVIEW Shared DLL VI would work. The eventual system will be passing in a string of XML with a large amount of
    data and returning XML.
    Thanks in advance,
    Jim

    Hello jprucha,
    This occurs because LabVIEW DLLs are not considered managed code. As such, we need to define the C# function as unsafe to be able to call unmanaged DLLs.
    You can find more information about C# and managed code at Microsoft's developer website linked below.
    MSDN Home Page
    Good luck with the development,
    Matt F
    Keep up to date on the latest PXI news at twitter.com/pxi

  • TO_NUMBER function on varchar2 column with numbers and strings

    I need to create a column in a view that converts a varchar2 column data to number. The problem is that some
    of the data have strings and some numbers. I get "ORA-01722: invalid number" error when Oracle tries to covert
    strings (e.g. 'ABCD') to number. What I need is to get a NULL value if the data is an invalid number.
    How can I rewrite the following to get NULL value is a string is invalid number?
    select to_number('abcd') numberColumn
    from dual
    thanx
    Alfred

    SQL> select * from test_char_num;
    ALPHA_NUM
    ABC
    DEF
    123
    234
    A12
    SQL> select decode(NVL(length(trim(translate(alpha_num, '1234567890', ' '))), 0),
      2                0, alpha_num, 'NULL') new_alpha_num
      3  from test_char_num;
    NEW_ALPHA_
    NULL
    NULL
    123
    234
    NULLP.S I am printing 'NULL' just to show the result, Please replace the 'NULL string with NULL value in SQL.
    Thx,
    Sri

  • Mixing HDs with FW400 and FW800 in a daisy chain

    I have a 360GB with two FW ports and two Quadra D2s with one FW400 and two FW800 ports. Using the three HDs -
    Can I Connect FW400 to FW400 then out via FW800 into FW800 then out via FW400 into my eMac?

    So it would seem that no matter how the two FW types are threaded between the three HDs the route is open and the chain runs at the 'slower' speed..
    As I have yet to format one of the Quadra's can I put it into the chain and then Format it, or should it be formatted with the orher two HDs diconnected from the chain?
    Cheers

  • [SOLVED] What's broken with clang++ and string.h?

    Not sure when this started:
    $ cat foo.cpp
    #include <cstring>
    $ clang++ -c foo.cpp # Works fine
    $ clang++ -O2 -c foo.cpp
    In file included from foo.cpp:1:
    In file included from /usr/bin/../lib64/gcc/x86_64-unknown-linux-gnu/4.9.2/../../../../include/c++/4.9.2/cstring:42:
    /usr/include/string.h:82:1: error: unknown type name '__extern_always_inline'
    __extern_always_inline void *
    ^
    /usr/include/string.h:82:24: error: expected unqualified-id
    __extern_always_inline void *
    fatal error: too many errors emitted, stopping now [-ferror-limit=]
    20 errors generated.
    Last edited by tavianator (2014-11-23 02:17:58)

    The upstream glibc-2.20 branch has one out of a pair of patches backported.   I will fix it both upstream and here today.

  • Ios 6 orientation doesn't work and boot time increases. How to solve these issues for dummy? I don't understand code and strings suggested by others.

    I just upgraded from ios 5 to ios 6 on my ipad2. Now orientation doesn't work properly. Boot time increase, it takes longer time to boot. Is there any configuration to solve these issues? I can't understand the explanation with code and strings found on google to solve the orientation issue. Any easy configuration for dummy ?

    It supports well for ios 5. I couldn't remember (5.x.x) exactly but I always keeps update for ios5 and the abnormality starts when I upgraded to ios 6.

  • Mixed results on iPad and iPhone 6 Plus with background image. How to fix this?

    Flash Professional CC
    I'm having an issue with adding images on iPhone 6 plus and iPad. I'm getting mixed results with two items: 1) a background image and 2) a button that should appear at the bottom left-hand corner on any device. In one case the background image appears enlarged and only shows about 30% of itself. In the other case, the bottom left-hand button appears about 50 pixels to the left when x=0. I also get different results when I set the following:
    stage.scaleMode = StageScaleMode.NO_SCALE;
    stage.align = StageAlign.TOP_LEFT;
    This does not produce the expected results. I would like to have consistent results across iPad and iPhone 6 plus, which seams to be an issue. The immediate fix for this is to leave the images on the stage instead of using addChild. I could then just stretch the background image so that it spans the whole screen. But I want to add the items dynamically for greater flexibility.
    Here are two cases:
    Case #1:
    This an iPhone 6 plus and you should notice 2 things. 1) There is black and white on both sides. The blue background SHOULD APPEAR ACROSS THE WHOLE SCREEN. 2) The red button in the corner SHOULD APPEAR IN THE LEFT MOST CORNER OF THE
    SCREEN.
    Case #2:
    This an iPhone 6 plus and I have set the scale X, Y to the stage.stageWidth/Height:
    mc_stageBackground_Main.scaleX = stage.stageWidth;
    mc_stageBackground_Main.scaleY = stage.stageHeight;
    This results in a close up of the background image.
    Here is the code that I'm using:
    import com.greensock.TweenLite;
    import com.greensock.easing.*;
    import flash.display.StageAlign;
    import flash.display.StageScaleMode;
    //When this is active the background image spans across the device (iPhone 6 plus) correctly. The main logo image does not line up correctly.
    /*stage.scaleMode = StageScaleMode.NO_SCALE;
    stage.align = StageAlign.TOP_LEFT;*/
    var main_logo:MC_LOGO_MAIN = new MC_LOGO_MAIN();
    var mainBackground_2208: MC_MAIN_BACKGROUND_2208 = new MC_MAIN_BACKGROUND_2208();
    var mainBackground_1024: MC_BACKGROUND_1024 = new MC_BACKGROUND_1024();
    var mainCorner: MC_MAINCORNER = new MC_MAINCORNER();
    var chapters: MC_CHAPTERS = new MC_CHAPTERS();
    var _stageWidth = 1024;
    if (stage.stageWidth > _stageWidth)
        //Add bigger background if the stage is bigger than 1024
        mainBackground_2208.x = stage.stageWidth/2;
        mainBackground_2208.y = stage.stageHeight/2;
        addChild(mainBackground_2208);
        //Using this code results in a very close up view of the stage on iPhone 6 plus  
        /*mc_stageBackground_Main.scaleX = stage.stageWidth;
        mc_stageBackground_Main.scaleY = stage.stageHeight;*/
        //Adds corner to the main screen.
        mainCorner.y = stage.stageHeight;
        mainCorner.x = (stage.stageWidth - stage.stageWidth);
        addChild(mainCorner);
        TweenLite.from(mainCorner, 1,{ height: 0, width: 0, delay:1, ease:Elastic.easeOut});
        //add logo to sit at 50 pixels from the top of the stage
        /*main_logo.x = stage.stageWidth/2;
        main_logo.y = (stage.stageHeight -stage.stageHeight + main_logo.height *.6);
        addChild(main_logo);
        TweenLite.from(main_logo, 1,{ y: -main_logo.height, ease:Elastic.easeOut});*/
    else
        trace ("The stage is 1024 or smaller");
        //Add 1024 background if stage is 1024 or smaller
        mainBackground_1024.x = stage.stageWidth/2;
        mainBackground_1024.y = stage.stageHeight/2;
        addChild(mainBackground_1024);
        //Adds corner to the main screen.
        mainCorner.y = stage.stageHeight;
        mainCorner.x = (stage.stageWidth - stage.stageWidth);
        addChild (mainCorner);
        TweenLite.from(mainCorner, 1,{ height: 0, width: 0, delay:1, ease:Elastic.easeOut});
        //adds chapters
        chapters.x = (stage.stageWidth - stage.stageWidth)+75;
        chapters.y = stage.stageHeight - 120;
        addChild(chapters);
        TweenLite.from(chapters, 1,{ height: 0, delay:.5, ease:Elastic.easeOut});  
        //adds the Main logo to sit at 50 pixels from the top of the stage
        main_logo.x = stage.stageWidth/2;
        main_logo.y = (stage.stageHeight -stage.stageHeight + main_logo.height *.6);
        addChild(main_logo);
        TweenLite.from(main_logo, 1,{ y: -main_logo.height, ease:Elastic.easeOut});

    On all of the devices go to settings - facetime - iphone cellular calls - oFF, this part of Apple continuity.

  • I am totally frustrated by the fact that now i have gone to iCloud and after a few synchs, my contacts are all mixed up with the wrong information.  For instance, my email and phone number comes up under someone else's name (a thousand contacts)

    I am totally frustrated by the fact that now i have gone to iCloud and after a few synchs, my contacts are all mixed up with the wrong information.  For instance, my email and phone number comes up under someone else's name (a thousand contacts).  I dont know how to repair this.  what a nightmare

    An icloud account is designed to be used by just one user.  If you have given your ID or set up your account on someone else's device, then their data will be mingled with your or worse.

  • Is there a way to change the pin color in iPhoto so I can pin my photos  and places from those from others.  i think it would be cool to see where my friends have also been but not mix it with mine.  Thanks

    s there a way to change the pin color in iPhoto so I can pin my photos  and places from those from others.  i think it would be cool to see where my friends have also been but not mix it with mine.  Thanks

    No
    Suggest to Apple
    You can make a smart album based on camera to seperate photos
    LN

  • Is there a way to make Movies and Home Videos show up in different sections on the apple tv instead of showing the home videos mixed in with the movies?

    I have several movies and home videos stored in itunes, when viewing these on appletv, it mixes all the movies and home videos together.
    I would like to beable to select either Movies or Home Videos when viewing on the Apple TV if this is possible...?

    You have 2 options:
    1. Create Video Playlists in iTunes (for example create one for Home movies, the other for Movies)
    You COULD make these Smart Playlists. (see below for one technique)
    NOTE: If you wish to do this don't miss the preference in Settings to enable Video Playlists at least  (at least in the latest ATV updates) I believe it's under Audio setting. Amazingly the default is NOT to show!! (had me going for quite a bit)
    2. Set up your Home Movies as "Music Videos" This has some gotchas:  like you'll probably want to choose the skip when shuffiling, also Now they'll appear in music lists. The only advantage to this is that it makes playlists more available on iOS devices since there are no Playlists displayed in the Videos App.... (yeah Apple's made this WAY confusing of late)
    If you wish to keep these clearly defined (especially for use with Smart Playlists.
    Select the movie
    Get Info (Edit Menu) (or Command-I Mac, Control-I, PC)
    Choose the "Video" Tab - you can select your desired type from the Media Kind pop up.
    Alternate method for setting up smart playlist of home movies would be to set the Genre to "Home Movie"
    Probably more than you needed to know - leigh

  • Since upgrading to 7.0.3 (iPhone 5 64gb, with iTunes Match enabled) all of my music wiped off my phone.  Downloading it again, most of the artwork has been mixed up with other artists, and I'm no longer able to stream or download over 3G? Any ideas?

    Since upgrading to 7.0.3 (iPhone 5, 64gb, with iTunes Match enabled) almost all of my music has vanished from my phone (weirdly some hasn't).
    Downloading it again, most of the artwork has been mixed up with other artists, and I'm no longer able to stream or download over 3G (all tracks greyed out), though my network settings etc are all set correctly.
    Lastly since upgrading to iOS 7.0.1 (and beyond) Genuis has become effectively useless: it continually asks me to connect to wi-fi, and if I do it creates playlists mostly composed of tracks by the same artists or those very obviously linked to them- previously it created brilliant, nuanced playlists.
    Are these things connected, and how do I fix them?

    I have done this on numerous occasions but I think that my Iphone has a defect. After many tries, reinstalls, deletion of content, changing content to be stored on external hard drive, deleting itunes and cleaning computer I managed to get all of the songs on and things seemed okay for a while.
    The problem returned about a week ago after downloading a new album from Itunes. I now have 12.5k of songs leaving 10gb spare on Iphone which should be more than enough room to operate properly. Last night it seemed to be dowloading ok (after doing all of the above again for the umpteenth time) this morning it revealed that it had just synched 2.5k of songs and 18gb of "other" on the contents bar. it wont synch now as it says its over capacity. So the 18gb of "other" would probably be corrupted data that means it must corrupt each song as it tries to synch it.
    The 2.5k of songs it did synch are working on the Iphone as is every song in the library on Itunes. I did completely delete the new album I bought and redownloaded it from the store then tried to synch just that album and it worked fine.
    Just about time to dump apple I think!

  • Can anyone help with icloud and apple accounts getting mixed up on 2 phones?

    Basically husband upgraded from 4s to 5c. Gave dad 4s. I tried to set his dad up with icloud and apple id but didn't realise husbands old sim card was in 4s. Now neither phone works and husband very annoyed his apple id and password don't work anymore. Please help!!!

    Hi Chris
    So husband got new phone. Was all set up and up and running when we left the shop
    Gave dad the old phone. It was locked to Vodafone so we had to ask them to unlock. He then got his three sim cut down to fit.
    Weeks after husband had his 5c we went to dads to set his 4s up. I upgraded it to latest software iOS something. Anyway didn't realise it was husbands old sim still in phone.
    After upgrade it asked me to set up apple account (I think) could have been icloud. Anyway I started setting it up with dads email and password choice. Husband then saw message on his 5c saying his dads email was being added to something on his phone.
    At this point I left alone but now when husband tries to use his apple id for apps etc it says invalid user id or password. It's as though the 2 have got mixed up. Bit it won't let him reset his password?
    Does this make sense?

  • When I forward an e-mail, I get a long string of gobblygook that goes with it and I cannot figure out how to eliminate it without having to delete it every time

    When I forward an e-mail, I get a long string of gobblygook that goes with it and I cannot figure out how to eliminate it without having to delete it every time I forward an e-mail. The following is only part of the string that I am talking about. How can I eliminate this from the e-mail?
    Here is part of an excerpt from one of the strings:
    From: - Mon Aug 19 18:12:47 2013
    X-Account-Key: account1
    X-UIDL: 065B31352CC6B3C0789DEA7954395B55
    X-Mozilla-Status: 0001
    X-Mozilla-Status2: 00000000
    X-Mozilla-Keys:
    Return-Path: <[email protected]>
    Received: from hrndva-mxlb.mail.rr.com ([10.128.255.126]) by hrndva-imta07.mail.rr.com with ESMTP id <20130819211326470.DBUO12525@hrndva-X-Roving-StreamId: 0

    Sorry, Firefox doesn't do email, it's strictly a web browser.
    If you are using Firefox to access your mail, you are using "web-mail". You need to seek support from your service provider or a forum for that service.
    If your problem is with Mozilla Thunderbird, see this forum for support.
    [https://support.mozillamessaging.com/en-US/home] <br />
    or this one <br />
    [http://forums.mozillazine.org/viewforum.php?f=39]

Maybe you are looking for

  • Table for Material Quantity and Value for particular month and year

    Hi All My requirement is that for a particular month and year I want to know the stock quantity and stock value for a particular material for a given plant.From which SAP table can I get this data as I want to fetch data for my Y report? Regards Sati

  • Help with Skip Level dimensions in OWB 10.2 (Paris)

    Hi all, I'm trying to understand how to set up and use a skip level dimension in OWB 10.2. A simplified version of my hierarchy would be: Plant - Equipment - Assembly - Item Where Some Items connect directly to equipment and others connect to assembl

  • Cannot access sapdb backend from Content Server?

    I am unable to access my sapdb from my Content Server via CSADMIN or with the /ContentServer.dll?serverInfo page. I run a Content Server on Unix - version 640, build 16. Here's what I've verified thus far: - SAPDB is up and running. - x_server proces

  • Can't update from template

    hi all, firstly, i am noob at dreamweaver.I encountered a problem applying my template in html code in my pages.After i add new links in template page ,dreamweaver warns me to update pages created before.i do ok but when i opened pages i see they are

  • Re: Load up problem on Satellite Pro A300

    Hi there, i am trying to sort out a laptop for a friend and have hit a bit of a wall...please could someone help asap!? When i start up the laptop the usual Toshiba logo and slogan appears, i then come to a black screen with two options; 1. launch st