migration C#, Java, C++ (day 9b), TextIO, Tuples

logo

Some basic stuff today. Tuples are not well-known. They are very useful for returning multiple types within one method. Tuples are immutable in C#. C++ is more relaxed about this. Reading or writing text files is nothing special as well. Anyway, consider that C# uses Unicode whereas C++ mainly deals with ASCII. I do not see C++ as a standard developer language. It is used to gain extra speed. So I won’t even touch the idea of Unicode in my examples. What is the meaning of sitting in front of your PC for hours just to get a result that you could get in another language within minutes.
The right approach is to mix languages.

TextIO and Tuples

using System;
using System.IO;

namespace DemoApp.ToCpp {
   public class Day9 {

      public static void Test() {
         try {
            string lDesktopPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + @"\";
            string lFile = lDesktopPath + "test.txt";
            string lText = "I see trees of green, red roses too.\nI see them bloom for me and you.\nAnd I think to myself what a wonderful world.\nI see skies of blue and clouds of white\n...";

            // write
            File.WriteAllText(lFile, lText);
            
            // read
            string lLoadResult = File.ReadAllText(lFile);
            Console.WriteLine(lLoadResult);

            // make trees blue
            lLoadResult = lLoadResult.Replace("green", "blue");
            Console.WriteLine("\nThe trees have just changed their colour:\n\n");
            Console.WriteLine(lLoadResult);

            // tuples
            Tuple<int, string, double> lTuple = new Tuple<int, string, double>(1, "2", 3.0);
            //lTuple.Item3 = 3.3; compiler error: readonly
            Console.WriteLine(lTuple.Item1 + " " + lTuple.Item2 + " " + lTuple.Item3);
         }
         catch (Exception ex) {
            Console.WriteLine(ex.Message);
         }

         Console.ReadLine();
      } //

   } // class
} // namespace

example output:
I see trees of green, red roses too.
I see them bloom for me and you.
And I think to myself what a wonderful world.
I see skies of blue and clouds of white

The trees have just changed their colour:

I see trees of blue, red roses too.
I see them bloom for me and you.
And I think to myself what a wonderful world.
I see skies of blue and clouds of white

1 2 3

#include <iostream>
#include <string>
#include <stdexcept>
#include <memory>
#include <sstream>
#include <fstream>
#include <algorithm>

using namespace std;

void StringToTextFile(const string &xFilename, const string &xText)  {
    ofstream lStream;
    lStream.open(xFilename.c_str());
    lStream << xText;
    lStream.close();
}

string TextFileToString(const string &xFilename)  {
    ostringstream lStringBuilder(ios::out | ios::binary);
    ifstream lStream(xFilename.c_str());
    string s;
    while (getline(lStream, s)) lStringBuilder << s << endl;
    return lStringBuilder.str();
}

int main() {
    try {
      string lDesktopPath = "C:\\Users\\YourUsername\\Desktop\\"; // no direct and portable C++ support
      string lFile = lDesktopPath + "test.txt";
      string lText = "I see trees of green, red roses too.\nI see them bloom for me and you.\nAnd I think to myself what a wonderful world.\nI see skies of blue and clouds of white\n...";

      // write
      StringToTextFile(lFile, lText);

      // read
      string lLoadResult = TextFileToString(lFile);
      cout << lLoadResult << endl;

      // make trees blue
      lLoadResult.replace(lLoadResult.find("green"), 5, "blue");
      cout << endl << "The trees have just changed their colour:" << endl << endl;
      cout << lLoadResult << endl;

      // tuples
      tuple<int, string, double> lTuple = make_tuple(1, "2", 3.0);
      cout << get<0>(lTuple) << " " << get<1>(lTuple) << " " << get<2>(lTuple) << endl;
      get<0, int, string, double>(lTuple) = 9;
      cout << get<0>(lTuple) << " " << get<1>(lTuple) << " " << get<2>(lTuple) << endl;

      int i;
      string s = "OOOPS";
      double d;
      tie (i, ignore, d) = lTuple; // unpack
      cout << i << " " << s << " " << d << endl;

      s = get<1>(lTuple);
      cout << s << endl;
    }
    catch (exception &ex) { cout << ex.what() << endl; }

    cin.get();
    return 0;
} //

example output:
I see trees of green, red roses too.
I see them bloom for me and you.
And I think to myself what a wonderful world.
I see skies of blue and clouds of white

The trees have just changed their colour:

I see trees of blue, red roses too.
I see them bloom for me and you.
And I think to myself what a wonderful world.
I see skies of blue and clouds of white

1 2 3
9 2 3
9 OOOPS 3
2

package DemoApp.ToCpp;

public final class Tuple<T, U, V> {

  // tuples are not supported by the standard libraries
  // this is a quick and dirty way to replicate a Triplet
  private final T _value0;
  private final U _value1;
  private final V _value2;

  public Tuple(T xValue0, U xValue1, V xValue2) {
    _value0 = xValue0;
    _value1 = xValue1;
    _value2 = xValue2;
  } // constructor

  public T get0() { return _value0; }
  public U get1() { return _value1; }
  public V get2() { return _value2; }
} // class
//-----------------------------------------------------------------------------
package DemoApp.ToCpp;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;

public class Day9 {  

  public static void main(String[] args) {
    try {
      String lDesktopPath = null;

      try {
        lDesktopPath = System.getProperty("user.home") + "/Desktop";
        lDesktopPath = lDesktopPath.replace("\\", "/");
        System.out.println("Desktop path: " + lDesktopPath);
      } catch (Exception e) {
        System.out.println("Exception caught =" + e.getMessage());
      }

      String lFile = lDesktopPath + "/test.txt";
      String lNewLine = System.getProperty("line.separator");
      String lText = "I see trees of green, red roses too." + lNewLine + "I see them bloom for me and you." + lNewLine + "And I think to myself what a wonderful world." + lNewLine + "I see skies of blue and clouds of white" + lNewLine + "...";

      // write  (try-with-resources statement, http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html)
      try (BufferedWriter lWriter = new BufferedWriter(new FileWriter(lFile))) {
        lWriter.write(lText);
      } catch (IOException ex) {
        System.out.println("IOException =" + ex.getMessage());
      }

      // read (all in one shot)
      StringBuilder lStringBuilder = new StringBuilder();
      String lLoadResult = null;
      try {
        Path lPath = Paths.get(lFile);
        List<String> lList = Files.readAllLines(lPath, StandardCharsets.UTF_8);
        for (String lLine : lList) { lStringBuilder.append(lLine); lStringBuilder.append(lNewLine); }
        lLoadResult = lStringBuilder.toString();        
        System.out.println(lLoadResult);
      } catch (IOException ex) {
        System.out.println("IOException =" + ex.getMessage());
      }

      // make trees blue
      if (lLoadResult != null) {
        lLoadResult = lLoadResult.replace("green", "blue");
        System.out.println("The trees have just changed their colour:\n");
        System.out.println(lLoadResult);
      }

      // tuples      
      Tuple<Integer, String, Double> lTuple = new Tuple<>(1, "2", 3.0);
      //lTuple.Item3 = 3.3; compiler error: readonly
      System.out.println(lTuple.get0() + " " + lTuple.get1() + " " + lTuple.get2());
    } catch (RuntimeException ex) {
      System.out.println(ex.getMessage());
    }

    new Scanner(System.in).nextLine();
  }

} // class

example output:
Desktop path: C:/Users/LvAdmin/Desktop
I see trees of green, red roses too.
I see them bloom for me and you.
And I think to myself what a wonderful world.
I see skies of blue and clouds of white

The trees have just changed their colour:

I see trees of blue, red roses too.
I see them bloom for me and you.
And I think to myself what a wonderful world.
I see skies of blue and clouds of white

1 2 3.0

About Bastian M.K. Ohta

Happiness only real when shared.

Posted on March 11, 2014, in Advanced, C#, C++, Java and tagged , , , , , , , , . Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: